<?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 authorizations limit 1');
    if(!empty($brEXist))
        $query = ' AND tech.id NOT IN (SELECT request_id FROM authorizations WHERE isdel = 0)';
   $sql ="SELECT 
                te.name , te.the_issuing_entity , bid.id, bid.session_date , m.member_name , tech.id AS tech_id
                FROM 
                tenderannouncement te , bidrequest bid , memberships m  , technicalopenion tech
                WHERE
                te.id=bid.op_id AND tech.request_details=bid.id AND bid.member_id=m.id AND tech.isdel=0".$query;
           $results = R::getAll($sql);
    $smarty->assign('requests', $results);
    $smarty->display("AuthorizationsView/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 
                auth.id AS auth_id,
                te.name AS tender_name, 
                te.the_issuing_entity, 
                m.member_name, 
                bid.session_date,
                auth.delegation_date,
                auth.image,
                auth.sys_date,
                u.employeename
            FROM authorizations auth
            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 auth.userid = u.userid
            WHERE auth.isdel = 0
            ORDER BY auth.id DESC";
    $showData = R::getAll($sql);
    $smarty->assign('showData', $showData);

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

    $smarty->display("AuthorizationsView/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('authorizations', $id);
   $sql = "SELECT 
                te.name, te.the_issuing_entity, bid.id, bid.session_date, m.member_name, tech.id AS tech_id
            FROM 
                tenderannouncement te, bidrequest bid, memberships m, technicalopenion tech
            WHERE
                te.id=bid.op_id AND tech.request_details=bid.id AND bid.member_id=m.id 
                AND (tech.id NOT IN (SELECT request_id FROM authorizations WHERE isdel = 0)OR tech.id = ? )";
   $requests = R::getAll($sql, [$showData->request_id]);
    
    $smarty->assign('showData', $showData);
    $smarty->assign('requests', $requests);
    $smarty->display("AuthorizationsView/edit.html");

    } elseif ($do == "report") {
   
    $sql = "SELECT 
                auth.id AS auth_id,
                te.name AS tender_name, 
                te.the_issuing_entity, 
                m.member_name, 
                bid.session_date,
                auth.delegation_date,
                auth.image,
                auth.sys_date,
                u.employeename
            FROM authorizations auth
            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 auth.userid = u.userid
            WHERE auth.isdel = 0
            ORDER BY auth.id DESC";
    $showData = R::getAll($sql);
    $smarty->assign('showData', $showData);

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

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

    } elseif ($do == "view") { //edit request
    $id = $_GET['id'];
 
    $showData = R::load('authorizations', $id);
   $sql = "SELECT 
                te.name, te.the_issuing_entity, bid.id, bid.session_date, m.member_name, tech.id AS tech_id
            FROM 
                tenderannouncement te, bidrequest bid, memberships m, technicalopenion tech
            WHERE
                te.id=bid.op_id AND tech.request_details=bid.id AND bid.member_id=m.id 
                AND (tech.id NOT IN (SELECT request_id FROM authorizations WHERE isdel = 0)OR tech.id = ? )";
   $requests = R::getAll($sql, [$showData->request_id]);
    
    $smarty->assign('showData', $showData);
    $smarty->assign('requests', $requests);
    $smarty->display("AuthorizationsView/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_id = $_POST['request'];
    $delegate_date = $_POST['delegate'];
    $image = uploadnew('image', False, 0, 0, 'Authorizations');
    $rdispense = R::dispense('authorizations');
    $rdispense->request_id = $request_id;
    $rdispense->delegation_date =$delegate_date;
    $rdispense->image = $image;
    $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_id = $_POST['request'];
    $image = uploadupdate('image', 'imageurl', False, 0, 0, 'Authorizations');
    $delegation_date = $_POST['delegate'];
    $rupdate = R::load('authorizations', $id);
    $rupdate->request_id = $request_id;
    $rupdate->image = $image;
    $rupdate->delegation_date = $delegation_date;
    $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('authorizations', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}