<?php

session_start();
ob_start();
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("add2SimpleReturn", "checkTotal");
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 ($do == "checkTotal") {
    $requestInput = file_get_contents('php://input');
    $input = json_decode($requestInput, true);

    $selectedChecks = isset($input['checks']) ? $input['checks'] : array();
    $totalPayments = 0;

    if (!empty($selectedChecks)) {
        $placeholders = implode(',', array_fill(0, count($selectedChecks), '?'));
        
        $totalPayments = R::getCell(
            "SELECT SUM(batch_value) FROM checks WHERE check_num IN ($placeholders)", 
            $selectedChecks
        );    
        
        $totalPayments = ($totalPayments !== null) ? (float)$totalPayments : 0;
    }

    header('Content-Type: application/json');
    echo json_encode(array('total_payments' => $totalPayments));
    exit; 
}

if (empty($do)) {
    //here the permission check
     $checks = R::findAll('checks', " isdel = 0");
     $showData = R::findAll('memberships', "request_status = 'accepted' AND isdel = 0");
     $entry = R::findAll('acc_journal_entry', "del = 0");




    $smarty->assign('checks', $checks);
    $smarty->assign('showData', $showData);
    $smarty->assign('entry', $entry);
    $smarty->display("formsview/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) {
        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 
                a.*, 
                u.employeename,
                member_name
            FROM forms a
           left JOIN memberships m ON a.member = m.id
            LEFT JOIN user u ON a.userid = u.userid 
            WHERE a.isdel = 0 
            
            ORDER BY a.id ";
            
    $showData = R::getAll($sql);
    $smarty->assign('showData', $showData);
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("formsview/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'];
         $checks = R::findAll('checks', " isdel = 0");
    $smarty->assign('checks', $checks);
     $members = R::findAll('memberships',"request_status = 'accepted' AND isdel = 0");
    $smarty->assign('members', $members);
     $entries = R::findAll('acc_journal_entry',"del = 0");
    $smarty->assign('entries', $entries);
    $showData = R::load('forms', $id);
    $smarty->assign('showData', $showData);
    $smarty->display("formsview/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() {
    $member = $_POST['member_name'];
    $entry_no = $_POST['entry_no']; 
    $comment = $_POST['comment'];
    $total_bank_value = $_POST['total_bank_value'];
      $checks = "";
    if (isset($_POST['checks']) && is_array($_POST['checks'])) {
        $checks = implode(' - ', array_filter($_POST['checks']));
    }
    $target_dir = "../upload/forms/";

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $rdispense = R::dispense('forms');
    $rdispense->entry_no = $entry_no;
    $rdispense->comment = $comment;
    $rdispense->member = $member;
    $rdispense->checks = $checks;
    $rdispense->total_bank_value = $_POST['total_bank_value'];
     $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/forms/" . $imgname);
            $images[] = $imgname;
        }
    }
    $rdispense->images = implode(',', $images);
    $rdispense->sysDate = 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'];
    $member = $_POST['member_name'];
    $entry_no = $_POST['entry_no']; 
    $checks = "";
    if (isset($_POST['checks']) && is_array($_POST['checks'])) {
        $checks = implode(' - ', array_filter($_POST['checks']));
    }
    $total_bank_value = $_POST['total_bank_value'];
    $comment = $_POST['comment'];
    $rupdate = R::load('forms', $id);
    $rupdate->entry_no = $entry_no;
    $rupdate->comment = $comment;
    $rupdate->member = $member;
    $rupdate->checks = $checks;
    $rupdate->total_bank_value = $total_bank_value;
    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/forms/" . $n);
                $files[] = $n;
            }
            return implode(',', $files);
        }
        return $_POST[$old];
    }
    $rupdate->images   = up('image', 'imageurl');
    $rupdate->isdel = 0;
 
    $id = R::store($rupdate);
}

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