<?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 extracts limit 1');
    if(!empty($brEXist))
    $query = ' AND sr.site_id NOT IN (SELECT ex.report_id FROM extracts ex WHERE ex.isdel = 0)';
    $sql = "SELECT 
              te.name AS tender_name, 
            te.the_issuing_entity, 
            bid.id AS bid_id, 
            bid.session_date, 
            m.member_name,
            tech.id AS tech_id, 
            auth.id AS auth_id, 
            assay.autho_id, 
            acc.assyas_id,  
            af.auth_id,
            sr.site_id            
        FROM sitereceipt sr
        INNER JOIN authaletter af ON sr.site_id = af.auth_id
        INNER JOIN finalletter ll ON af.auth_id = ll.final_id
        INNER JOIN firstletter fl ON ll.final_id = fl.accept_id
        INNER JOIN acceptance acc ON fl.accept_id = acc.assyas_id
        INNER JOIN assays assay ON acc.assyas_id = assay.autho_id
        INNER JOIN authorizations auth ON assay.autho_id = auth.id
        INNER JOIN technicalopenion tech ON auth.request_id = tech.id
        INNER JOIN bidrequest bid ON tech.request_details = bid.id
        INNER JOIN tenderannouncement te ON bid.op_id = te.id
        INNER JOIN memberships m ON bid.member_id = m.id
          WHERE sr.isdel = 0" . $query . " GROUP BY sr.site_id";
  $results = R::getAll($sql);
    $smarty->assign('requests', $results);
    $smarty->display("extractsview/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 
            te.name AS tender_name, 
            te.the_issuing_entity, 
            bid.id AS bid_id, 
            m.member_name, 
            tech.id AS tech_id, 
            auth.id AS auth_id,
            assay.id AS assay_id,
            acc.id AS acc_id,
            acc.comment AS acc_comment,
            ex.id AS ex_id,
            ex.comment AS ex_comment,
            ex.workforce,
            ex.insurance,
            ex.extract_value,
            ex.extract_date,
            ex.sys_date,
            u.employeename
        FROM extracts ex
        INNER JOIN sitereceipt sr ON ex.report_id = sr.site_id
        INNER JOIN authaletter af ON sr.site_id = af.auth_id
        INNER JOIN finalletter ll ON af.auth_id = ll.final_id
        INNER JOIN firstletter fl ON ll.final_id = fl.accept_id
        INNER JOIN acceptance acc ON fl.accept_id = acc.assyas_id
        INNER JOIN assays assay ON acc.assyas_id = assay.autho_id
        INNER JOIN authorizations auth ON assay.autho_id = auth.id
        INNER JOIN technicalopenion tech ON auth.request_id = tech.id
        INNER JOIN bidrequest bid ON tech.request_details = bid.id
        INNER JOIN tenderannouncement te ON bid.op_id = te.id
        INNER JOIN memberships m ON bid.member_id = m.id
        INNER JOIN user u ON ex.userid = u.userid
        WHERE sr.isdel = 0 AND af.isdel = 0 GROUP BY sr.site_id";
    $showData =R::getAll($sql);
    $smarty->assign('showData', $showData);

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

    $smarty->display("extractsview/show.html");
    $smarty->assign("customCheck", 1);
} 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('extracts', $id);
   $sql = "SELECT 
                sr.site_id,
                te.name AS tender_name, 
                te.the_issuing_entity, 
                bid.session_date,
                m.member_name,
                ex.id AS ex_id
            FROM sitereceipt sr
            INNER JOIN authaletter af ON sr.site_id = af.auth_id
            INNER JOIN finalletter ll ON af.auth_id = ll.final_id
            INNER JOIN firstletter fl ON ll.final_id = fl.accept_id
            INNER JOIN acceptance acc ON fl.accept_id = acc.assyas_id
            INNER JOIN assays assay ON acc.assyas_id = assay.autho_id
            INNER JOIN authorizations auth ON assay.autho_id = auth.id
            INNER JOIN technicalopenion tech ON auth.request_id = tech.id
            INNER JOIN bidrequest bid ON tech.request_details = bid.id
            INNER JOIN tenderannouncement te ON bid.op_id = te.id
            INNER JOIN memberships m ON bid.member_id = m.id
            LEFT JOIN extracts ex ON sr.site_id = ex.report_id
            WHERE sr.isdel = 0 
            AND (ex.id IS NULL OR ex.report_id = ?)
            GROUP BY sr.site_id";
        $relatedInfo = R::getAll($sql, [$showData->report_id]);
        $smarty->assign('showData', $showData);
        $smarty->assign('allOptions', $allRequests);
        $smarty->assign('relatedInfo', $relatedInfo);
        $smarty->display("extractsview/edit.html");

        } elseif ($do == "report") {
   
    $sql = "SELECT 
            te.name AS tender_name, 
            te.the_issuing_entity, 
            bid.id AS bid_id, 
            m.member_name, 
            tech.id AS tech_id, 
            auth.id AS auth_id,
            assay.id AS assay_id,
            acc.id AS acc_id,
            acc.comment AS acc_comment,
            ex.id AS ex_id,
            ex.comment AS ex_comment,
            ex.workforce,
            ex.insurance,
            ex.extract_value,
            ex.extract_date,
            ex.sys_date,
            u.employeename
        FROM extracts ex
        INNER JOIN sitereceipt sr ON ex.report_id = sr.site_id
        INNER JOIN authaletter af ON sr.site_id = af.auth_id
        INNER JOIN finalletter ll ON af.auth_id = ll.final_id
        INNER JOIN firstletter fl ON ll.final_id = fl.accept_id
        INNER JOIN acceptance acc ON fl.accept_id = acc.assyas_id
        INNER JOIN assays assay ON acc.assyas_id = assay.autho_id
        INNER JOIN authorizations auth ON assay.autho_id = auth.id
        INNER JOIN technicalopenion tech ON auth.request_id = tech.id
        INNER JOIN bidrequest bid ON tech.request_details = bid.id
        INNER JOIN tenderannouncement te ON bid.op_id = te.id
        INNER JOIN memberships m ON bid.member_id = m.id
        INNER JOIN user u ON ex.userid = u.userid
        WHERE sr.isdel = 0 AND af.isdel = 0 GROUP BY sr.site_id";
    $showData =R::getAll($sql);
    $smarty->assign('showData', $showData);

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

    $smarty->display("extractsview/report.html");
    $smarty->assign("customCheck", 1);
    } elseif ($do == "view") { //edit request
    $id = $_GET['id'];
    
    $showData = R::load('extracts', $id);
   $sql = "SELECT 
                sr.site_id,
                te.name AS tender_name, 
                te.the_issuing_entity, 
                bid.session_date,
                m.member_name,
                ex.id AS ex_id
            FROM sitereceipt sr
            INNER JOIN authaletter af ON sr.site_id = af.auth_id
            INNER JOIN finalletter ll ON af.auth_id = ll.final_id
            INNER JOIN firstletter fl ON ll.final_id = fl.accept_id
            INNER JOIN acceptance acc ON fl.accept_id = acc.assyas_id
            INNER JOIN assays assay ON acc.assyas_id = assay.autho_id
            INNER JOIN authorizations auth ON assay.autho_id = auth.id
            INNER JOIN technicalopenion tech ON auth.request_id = tech.id
            INNER JOIN bidrequest bid ON tech.request_details = bid.id
            INNER JOIN tenderannouncement te ON bid.op_id = te.id
            INNER JOIN memberships m ON bid.member_id = m.id
            LEFT JOIN extracts ex ON sr.site_id = ex.report_id
            WHERE sr.isdel = 0 
            AND (ex.id IS NULL OR ex.report_id = ?)
            GROUP BY sr.site_id";
        $relatedInfo = R::getAll($sql, [$showData->report_id]);
        $smarty->assign('showData', $showData);
        $smarty->assign('allOptions', $allRequests);
        $smarty->assign('relatedInfo', $relatedInfo);
        $smarty->display("extractsview/view.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() {
    $request = $_POST['request'];
    $comment = $_POST['comment']; 
    $people = floatval($_POST['people']);
    $insurance = $_POST['insurance'];
    $value = $_POST['value'];
    $date = $_POST['date'];
    $target_dir = "../upload/extracts/";

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $rdispense = R::dispense('extracts');
    $rdispense->report_id= $request;
    $rdispense->workforce = $people;
    $rdispense->insurance = $insurance;
    $rdispense->extract_value = $value;
    $rdispense->extract_date = $date;
    $rdispense->comment = $comment;
    

        $images = [];
    foreach ($_FILES['image']['name'] as $key => $val) {
        if ($_FILES['image']['tmp_name'][$key] != "") {
            $imgname = time() . "_" . $_FILES['image']['name'][$key];
            move_uploaded_file($_FILES['image']['tmp_name'][$key], "../upload/extracts/" . $imgname);
            $images[] = $imgname;
        }
    }
    $rdispense->extract_files = implode(',', $images);
    $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'];
    $request = $_POST['request'];
    $comment = $_POST['comment']; 
    $people = $_POST['people'];
    $insurance = $_POST['insurance'];
    $value = $_POST['value'];
    $date = $_POST['date'];
    $rupdate = R::load('extracts', $id);
    $rupdate->report_id= $request;
    $rupdate->workforce = $people;
    $rupdate->insurance = $insurance;
    $rupdate->extract_value = $value;
    $rupdate->extract_date = $date;
    $rupdate->comment = $comment;
    function up($input, $old) {
        if (!empty($_FILES[$input]['name'][0])) {
            $files = [];
            foreach ($_FILES[$input]['name'] as $k => $v) {
                $n = time() . "_" . rand(111, 999) . "_" . $v;
                move_uploaded_file($_FILES[$input]['tmp_name'][$k], "../upload/extracts/" . $n);
                $files[] = $n;
            }
            return implode(',', $files);
        }
        return $_POST[$old];
    }
    $rupdate->extract_files   = up('image', 'imageurl');
     $rupdate->sys_date = date("Y-m-d H:i:s");
    $rupdate->userid = $_SESSION['userid'];
    $rupdate->isdel = 0;
    
   
    $id = R::store($rupdate);
}

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