<?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)) {
    $members = R::findAll('memberships', "isdel = 0");
    $smarty->assign('members', $members);
    $smarty->display("checksview/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") {
  $status = isset($_GET['status']) ? (int)$_GET['status'] : 0;
   $sql = "SELECT 
                c.*, 
                u.employeename,
                m.member_name
            FROM checks c
            LEFT JOIN user u ON c.userid = u.userid 
            LEFT JOIN memberships m ON c.member_id = m.id 
            WHERE c.isdel = 0 
            ORDER BY c.id ";
            
    $showData = R::getAll($sql);
    $smarty->assign('showData', $showData);
    $smarty->assign('current_status', $status);

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

    $smarty->display("checksview/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('checks', $id);
    $members = R::findAll('memberships', "isdel = 0");
    $smarty->assign('showData', $showData);
    $smarty->assign('current_status', $showData->status);
    $smarty->assign('members', $members);
    
    $smarty->display("checksview/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['batch_num'];
    $batch_value = $_POST['batch_value']; 
    $check_num = $_POST['check_num'];
    $bank = $_POST['bank'];
    $details = $_POST['details'];
    $comment = $_POST['comment'];
    $member = $_POST['member_id'];
     $target_dir = "../upload/checks/";

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $rdispense = R::dispense('checks');
    $rdispense->batch_num = $num;
    $rdispense->check_num = $check_num;
    $rdispense->bank = $bank;
    $rdispense->batch_value = $batch_value;
    $rdispense->details = $details;
    $rdispense->comment = $comment;
    $rdispense->member_id = $member;
     $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/checks/" . $imgname);
            $images[] = $imgname;
        }
    }
    $rdispense->images = implode(',', $images);
     $check_image = [];
    foreach ($_FILES['check_image']['name'] as $key => $val) {
        if ($_FILES['check_image']['tmp_name'][$key] != "") {
            $imgname = time() . "_" . $_FILES['check_image']['name'][$key];
            move_uploaded_file($_FILES['check_image']['tmp_name'][$key], "../upload/checks/" . $imgname);
            $check_image[] = $imgname;
        }
    }
    $rdispense->check_image = implode(',', $check_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'];
    $num = $_POST['batch_num'];
    $batch_value = $_POST['batch_value']; 
    $check_num = $_POST['check_num'];
    $bank = $_POST['bank'];
    $details = $_POST['details'];
    $comment = $_POST['comment'];
    $member = $_POST['member_id'];
    $rupdate = R::load('checks', $id);
    $rupdate->batch_num = $num;
    $rupdate->batch_value = $batch_value;
    $rupdate->check_num = $check_num;
    $rupdate->bank = $bank;
    $rupdate->details = $details;
    $rupdate->comment = $comment;
    $rupdate->member_id = $member;
    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/checks/" . $n);
                $files[] = $n;
            }
            return implode(',', $files);
        }
        return $_POST[$old];
    }
    $rupdate->images   = up('image', 'imageurl');
    $rupdate->check_image   = up('check_image', 'check_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('checks', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}