<?php

session_start();
ob_start();
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("add2SimpleReturn");
include("initiateStaticSessionCommingWithCurl.php");
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    array_push($ajaxDoArr, $do);
}

if (!in_array($do, $ajaxDoArr)) {
    include("../public/impOpreation.php");
}



include_once("../public/config.php");
include("../library/newUplode/uploadfunctions.php");


require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');




//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");


if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("header.html");
    }
}



$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

$today = date("Y-m-d");
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
   
    $query = '';
     $brEXist = R::getRow('select * from technicalopenion limit 1');
     if(!empty($brEXist))
        $query = ' AND bo.request_details NOT IN (SELECT request_details FROM technicalopenion WHERE isdel = 0)';
        $sql = "SELECT bo.id as bo_id, bo.request_details, ta.name as tender_name, m.member_name 
            FROM boardopenion bo
            JOIN bidrequest br ON bo.request_details = br.id
            JOIN tenderannouncement ta ON br.op_id = ta.id
            JOIN memberships m ON br.member_id = m.id
            WHERE bo.board_openion = 0 
            AND bo.isdel = 0 ".$query;
            
    $results = R::getAll($sql);
    $smarty->assign('requests', $results);
    $smarty->display("technicalOpenionView/add.html");
} elseif ($do == "add") {
    try { 
    
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        echo $e;
        die();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "show") {
  
    $sql = "SELECT teo.*, ta.name as tender_name, m.member_name, u.employeename
            FROM technicalopenion teo
            LEFT JOIN bidrequest br ON teo.request_details = br.id
            LEFT JOIN tenderannouncement ta ON br.op_id = ta.id
            LEFT JOIN memberships m ON br.member_id = m.id
            LEFT JOIN user u ON teo.userid = u.userid
            WHERE teo.isdel = 0 
            ORDER BY teo.id DESC";
    $results = R::getAll($sql);
    $smarty->assign('showData', $results);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("technicalOpenionView/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "report") {
  
    $sql = "SELECT teo.*, ta.name as tender_name, m.member_name, u.employeename
            FROM technicalopenion teo
            LEFT JOIN bidrequest br ON teo.request_details = br.id
            LEFT JOIN tenderannouncement ta ON br.op_id = ta.id
            LEFT JOIN memberships m ON br.member_id = m.id
            LEFT JOIN user u ON teo.userid = u.userid
            WHERE teo.isdel = 0 
            ORDER BY teo.id DESC";
    $results = R::getAll($sql);
    $smarty->assign('showData', $results);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("technicalOpenionView/report.html");
    $smarty->assign("customCheck", 1);

    } elseif ($do == "view") { //edit request
    $id = $_GET['id'];
   
    $showData = R::load('technicalopenion', $id);
    $sql = "SELECT bo.*, ta.name as tender_name, m.member_name 
            FROM boardopenion bo
            JOIN bidrequest br ON bo.request_details = br.id
            JOIN tenderannouncement ta ON br.op_id = ta.id
            JOIN memberships m ON br.member_id = m.id
            WHERE bo.isdel = 0 AND bo.board_openion = 0 
            AND (bo.request_details NOT IN (SELECT request_details FROM technicalopenion WHERE isdel = 0 AND id != ?) 
                 OR bo.request_details = ?)";
   $requests = R::getAll($sql, [$id, $showData->request_details]);
    if (!empty($showData->image)) {
        $showData->image_list = explode(',', $showData->image);
    } else {
        $showData->image_list = [];
    }
    
    $smarty->assign('showData', $showData);
    $smarty->assign('requests', $requests);
    $smarty->display("technicalOpenionView/view.html");
} elseif ($do == "deleteFinaly") {
    try {
        $id = (int) $_GET['id'];
        deleteFinaly($id);

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "edit") { //edit request
    $id = $_GET['id'];
   
    $showData = R::load('technicalopenion', $id);
    $sql = "SELECT bo.*, ta.name as tender_name, m.member_name 
            FROM boardopenion bo
            JOIN bidrequest br ON bo.request_details = br.id
            JOIN tenderannouncement ta ON br.op_id = ta.id
            JOIN memberships m ON br.member_id = m.id
            WHERE bo.isdel = 0 AND bo.board_openion = 0 
            AND (bo.request_details NOT IN (SELECT request_details FROM technicalopenion WHERE isdel = 0 AND id != ?) 
                 OR bo.request_details = ?)";
   $requests = R::getAll($sql, [$id, $showData->request_details]);
    if (!empty($showData->image)) {
        $showData->image_list = explode(',', $showData->image);
    } else {
        $showData->image_list = [];
    }
    
    $smarty->assign('showData', $showData);
    $smarty->assign('requests', $requests);
    $smarty->display("technicalOpenionView/edit.html");
} elseif ($do == "update") { //edit update
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}


$smarty->assign("customValidation", 1);

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("footer.html");
    }
}

/* ===============================
  function in this CONTROLLER
  ================================ */

// add in tenderannouncement tbl
function add() {
    $num = $_POST['num'];
    $openion = $_POST['openion'];
    $boardRecord = R::load('boardopenion', $num);
    $real_request_id = $boardRecord->request_details;
    $uploadedFiles = [];
    $targetDir = "../upload/technicalOpenion/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
   if (isset($_FILES['image'])) {
        foreach ($_FILES['image']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['image']['name'][$key] != "") {
                $fileName = time() . "_" . $_FILES['image']['name'][$key];
                $targetFilePath = $targetDir . $fileName;
                if (move_uploaded_file($tmp_name, $targetFilePath)) {
                    $uploadedFiles[] = $fileName;
                }
            }
        }
    }
    $finalImagesPath = implode(',', $uploadedFiles);
    $rdispense = R::dispense('technicalopenion');
    $rdispense->request_details = $real_request_id;
    $rdispense->technical_openion = $openion;
    $rdispense->image = $finalImagesPath ;
    $rdispense->sys_date = date("Y-m-d H:i:s");
    $rdispense->userid = $_SESSION['userid'];
    $rdispense->isdel = 0;
   
    $id = R::store($rdispense);
    return $id;
}

function update() {

    $id = $_POST['id'];
    $num = $_POST['num'];
    $openion = $_POST['openion'];
    $image = $_POST['image'];
    $rupdate = R::load('technicalopenion', $id);
    $boardRecord = R::load('boardopenion', $num);
    $real_request_id = $boardRecord->request_details;
    function up($input, $old_name) {
        $targetDir = "../upload/technicalOpenion/";
        if (!empty($_FILES[$input]['name'][0])) {
            $old_files_string = $_POST[$old_name];
            if (!empty($old_files_string)) {
                $old_files = explode(',', $old_files_string);
                foreach ($old_files as $f) {
                    $f = trim($f);
                    if ($f != "" && file_exists($targetDir . $f)) {
                        @unlink($targetDir . $f);
                    }
                }
            }

            $files = [];
            foreach ($_FILES[$input]['name'] as $k => $v) {
                if ($_FILES[$input]['name'][$k] != "") {
                    $extension = pathinfo($v, PATHINFO_EXTENSION);
                    $n = time() . "_" . rand(111, 999) . "." . $extension; 
                    move_uploaded_file($_FILES[$input]['tmp_name'][$k], $targetDir . $n);
                    $files[] = $n;
                }
            }
            return implode(',', $files);
        }
        return $_POST[$old_name]; 
    }

    $rupdate->request_details = $real_request_id; 
    $rupdate->technical_openion = $openion;
    $rupdate->image = up('image', 'imageurl'); 
    $rupdate->sys_date = date("Y-m-d H:i:s");
    $rupdate->userid = $_SESSION['userid'];
    $rupdate->isdel = 0;

  
    R::store($rupdate);
}

function deleteFinaly($id) { 
    
    $rupdates = R::load('technicalopenion', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}