<?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');
include '../library/Classes/PHPExcel/IOFactory.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
     $sql = "SELECT * FROM employeesdetails WHERE isdel=0";
    $showData = R::getAll($sql);
    $smarty->assign("showData", $showData);
    $smarty->display("salariesview/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") {
   
    $month = isset($_REQUEST['month']) ? (int)$_REQUEST['month'] : 0;

   
    if ($month > 0) {
        $sql = "SELECT s.*, u.employeename, e.name 
                FROM salaries s
                LEFT JOIN user u ON s.userid = u.userid 
                LEFT JOIN employeesdetails e ON s.name = e.id 
                WHERE s.isdel = 0 AND s.month = ?
                ";
        $showData = R::getAll($sql, [$month]);
    } else {
        $showData = []; 
    }

    $smarty->assign('showData', $showData);
    $smarty->assign('currentMonth', $month);

    
    if (isset($_GET['ajax'])) {
        $smarty->display("salariesview/table_rows.html"); 
        exit;
    }

  
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->assign("customCheck", 1);
    $smarty->display("salariesview/show.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 == "ajax_update") {
    ob_clean(); 
    try {
        $id     = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $column = isset($_POST['column']) ? trim($_POST['column']) : '';
        $value  = isset($_POST['value']) ? trim($_POST['value']) : '';
        $allowed = [
            'salary','due_q','due_j',
            'earn_q','earn_j',
            'stamp_q','stamp_j',
            's_q','s_j',
            'net_q','net_j',
            'totaldeductions'
        ];

        if ($id <= 0) {
            echo "error_invalid_id"; exit;
        }

        if (!in_array($column, $allowed)) {
            echo "error_invalid_column"; exit;
        }

        $pay = R::load('salaries', $id);
        if (!$pay->id) {
            echo "error_id_not_found"; exit;
        }

       
        if (in_array($column, ['salary', 'totaldeductions'])) {
            $pay->$column = (float)$value;
        } else {
            $pay->$column = (int)$value;
        }

        R::store($pay);

        echo "success";

    } catch (Exception $e) {
        echo "error_" . $e->getMessage();
    }
    exit; 

} elseif ($do == "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 == "importExcel") { 
    try {
        addSalariesByMonthExcel();
        header("location:?do=show&status=success");
    } catch (Exception $e) {
        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() {
   
    $name = $_POST['name'];
    $month = $_POST['month'];
    $salary = (float)$_POST['salary'];
 
    $earn   = (float)$_POST['earn'];
   
    $due_q =(int) $_POST['due_q'];
    $due_j =(int) $_POST['due_j'];
    $stamp_q =(int) $_POST['stamp_q'];
    $stamp_j =(int) $_POST['stamp_j'];
    $s_q =(int) $_POST['s_q'];
    $s_j =(int) $_POST['s_j'];
    $net_q =(int) $_POST['net_q'];
    $net_j =(int) $_POST['net_j'];

   $stamp_total = $stamp_j + ($stamp_q / 100);
    $s_total     = $s_j + ($s_q / 100);
    $totaldeductions = $earn + $stamp_total + $s_total;
    $comment= $_POST['comment']; 
    
    $rdispense = R::dispense('salaries');
    $rdispense->name= $name;
    $rdispense->month = $month;
    $rdispense->salary = $salary;
    $rdispense->due_q = $due_q;
    $rdispense->due_j = $due_j;
    $rdispense->stamp_q = $stamp_q;
    $rdispense->stamp_j = $stamp_j;
    $rdispense->s_q = $s_q;
    $rdispense->s_j = $s_j;
    $rdispense->net_q = $net_q;
    $rdispense->net_j = $net_j;

   
   $rdispense->earn_q = (int)$_POST['earn_q'];
    $rdispense->earn_j = (int)$_POST['earn_j'];
    $rdispense->totaldeductions = $totaldeductions;
   
    $rdispense->comment = $comment;
   
    $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'];
   $name = $_POST['name'];
    $month = $_POST['month'];
    $salary = (float)$_POST['salary'];
 
    $earn   = (float)$_POST['earn'];
   
    $due_q =(int) $_POST['due_q'];
    $due_j =(int) $_POST['due_j'];
    $stamp_q =(int) $_POST['stamp_q'];
    $stamp_j =(int) $_POST['stamp_j'];
    $s_q =(int) $_POST['s_q'];
    $s_j =(int) $_POST['s_j'];
    $net_q =(int) $_POST['net_q'];
    $net_j =(int) $_POST['net_j'];

   $stamp_total = $stamp_j + ($stamp_q / 100);
    $s_total     = $s_j + ($s_q / 100);
    $totaldeductions = $earn + $stamp_total + $s_total;
    $comment= $_POST['comment']; 
    $rupdate = R::load('salaries', $id);
    $rupdate->name= $name;
    $rupdate->month = $month;
    $rupdate->salary = $salary;
    $rupdate->due_q = $due_q;
    $rupdate->due_j = $due_j;
    $rupdate->stamp_q = $stamp_q;
    $rupdate->stamp_j = $stamp_j;
    $rupdate->s_q = $s_q;
    $rupdate->s_j = $s_j;
    $rupdate->net_q = $net_q;
    $rupdate->net_j = $net_j;

   
    $rupdate->earn_q = (int)$_POST['earn_q'];
    $rupdate->earn_j = (int)$_POST['earn_j'];
    $rupdate->totaldeductions = $totaldeductions;
   
    $rupdate->comment = $comment;
   
    $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('salaries', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}


function addSalariesByMonthExcel() {
    global $today;
    $userId = $_SESSION['userid'];

    if (!isset($_FILES['salariessheet'])) return false;
    $selectedMonth = isset($_POST['month']) ? (int)$_POST['month'] : 0;

    $excelfileName = uploadnew('salariessheet', false, 0, 0, 'salaries', 7);
    $inputFileName = "../upload/salaries/" . $excelfileName;

    try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $count = 0;

        for ($row = 7; $row <= $highestRow; $row++) {
            $cellValue = $sheet->getCell('B' . $row)->getValue();
            $rawName = ($cellValue instanceof PHPExcel_RichText) ? $cellValue->getPlainText() : $cellValue;
            $rawName = trim($rawName);

            if (empty($rawName) || in_array($rawName, ["الاسم", "الاجمالي", "إجمالي", "Total"])) {
                if ($row > 10) break;
                continue;
            }


            $cleanName = str_replace(['أ','إ','آ','ة','ى'], ['ا','ا','ا','ه','ي'], $rawName);
            $cleanName = preg_replace('/\s+/', ' ', $cleanName); 

           
            $employee = R::findOne('employeesdetails', 
                "REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(name, 'أ', 'ا'), 'إ', 'ا'), 'آ', 'ا'), 'ة', 'ه'), 'ى', 'ي') LIKE ?", 
                ["%$cleanName%"]
            );

            if ($employee) {
               
                $pay = R::findOne('salaries', 'name = ? AND month = ? AND isdel = 0', [$employee->id, $selectedMonth]);
                
                if (!$pay) {
                  
                    $pay = R::dispense('salaries');
                }

                $pay->name    = (int)$employee->id;
                $pay->month   = (int)$selectedMonth;

               
                $pay->salary  = (float)$sheet->getCell('C' . $row)->getCalculatedValue();  
                $pay->due_q   = (int)$sheet->getCell('D' . $row)->getCalculatedValue();    
                $pay->due_j   = (int)$sheet->getCell('E' . $row)->getCalculatedValue();    
                $pay->earn_q  = (int)$sheet->getCell('F' . $row)->getCalculatedValue();    
                $pay->earn_j  = (int)$sheet->getCell('G' . $row)->getCalculatedValue();    
                $pay->stamp_q = (int)$sheet->getCell('H' . $row)->getCalculatedValue();    
                $pay->stamp_j = (int)$sheet->getCell('I' . $row)->getCalculatedValue();    
                $pay->s_q     = (int)$sheet->getCell('J' . $row)->getCalculatedValue();    
                $pay->s_j     = (int)$sheet->getCell('K' . $row)->getCalculatedValue();   
                $pay->totaldeductions = (float)$sheet->getCell('L' . $row)->getCalculatedValue(); 
                $pay->net_q   = (int)$sheet->getCell('M' . $row)->getCalculatedValue();   
                $pay->net_j   = (int)$sheet->getCell('N' . $row)->getCalculatedValue();   

                $pay->sys_date = date("Y-m-d H:i:s");
                $pay->userid   = $userId;
                $pay->isdel    = 0;

                R::store($pay);
                $count++;
            }
        }

      
    } catch (Exception $e) { die('خطأ: ' . $e->getMessage()); }
}