<?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("permanentemployeeview/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 pe.*, u.employeename, e.name 
                FROM permanentemployee pe
                LEFT JOIN user u ON pe.userid = u.userid 
                LEFT JOIN employeesdetails e ON pe.name = e.id 
                WHERE pe.isdel = 0 AND pe.month = ?
                ";
        $showData = R::getAll($sql, [$month]);
    } else {
        $showData = []; 
    }

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

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

  
    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->assign("customCheck", 1);
    $smarty->display("permanentemployeeview/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','bonus','comp_share',
            'free_allowance',
            'act_allowance','living_cost',
            'social_bonus','move_allowance',
            'other_allowance','efforts',
            'monthly_grant','good_bonus',
            'total_earn','work_share',
            'service','advance',
            'comp_loan','service_advance',
            'service_loan','stamp',
            'tax','previous_taxes',
            'debets','absence',
            'penalties','deductions',
            'net'
        ];

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

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

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

       
        if (in_array($column, ['permanentemployee', 'deductions'])) {
            $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 {
      addRewardsByMonthExcel();
        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 = $_POST['salary'];
    $bonus   =$_POST['bonus'];
    $comp_share = $_POST['comp_share'];
    $free_allowance = $_POST['free_allowance'];
    $act_allowance = $_POST['act_allowance'];
    $living_cost = $_POST['living_cost'];
    $social_bonus = $_POST['social_bonus'];
    $move_allowance = $_POST['move_allowance'];
    $other_allowance = $_POST['other_allowance'];
    $efforts = $_POST['efforts'];
    $monthly_grant = $_POST['monthly_grant'];
    $good_bonus = $_POST['good_bonus'];
    $total_earn = $_POST['total_earn'];
    $work_share = $_POST['work_share'];
    $service = $_POST['service'];
    $advance = $_POST['advance'];
    $comp_loan = $_POST['comp_loan'];
    $service_advance = $_POST['service_advance'];
    $service_loan = $_POST['service_loan'];
    $stamp = $_POST['stamp'];
    $tax = $_POST['tax'];
    $previous_taxes = $_POST['previous_taxes'];
    $debets = $_POST['debets'];
    $absence = $_POST['absence'];
    $penalties = $_POST['penalties'];
    $deductions = $_POST['deductions'];
    $net = $_POST['net'];
    $rdispense = R::dispense('permanentemployee');
    $rdispense->name= $name;
    $rdispense->month = $month;
    $rdispense->salary = $salary;
    $rdispense->bonus = $bonus;
    $rdispense->comp_share = $comp_share;
    $rdispense->free_allowance = $free_allowance;
    $rdispense->act_allowance = $act_allowance;
    $rdispense->living_cost = $living_cost;
    $rdispense->social_bonus = $social_bonus;
    $rdispense->move_allowance = $move_allowance;
    $rdispense->other_allowance = $other_allowance;
    $rdispense->efforts = $efforts;
    $rdispense->monthly_grant = $monthly_grant;
    $rdispense->good_bonus = $good_bonus;
    $rdispense->total_earn = $total_earn;
    $rdispense->work_share = $work_share;
    $rdispense->service = $service;
    $rdispense->advance = $advance;
    $rdispense->comp_loan = $comp_loan;
    $rdispense->service_advance = $service_advance;
    $rdispense->service_loan = $service_loan;
    $rdispense->stamp = $stamp;
    $rdispense->tax = $tax;
    $rdispense->previous_taxes = $previous_taxes;
    $rdispense->debets = $debets;
    $rdispense->absence = $absence;
    $rdispense->penalties = $penalties;
    $rdispense->deductions = $deductions;
    $rdispense->net = $net;
    $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 = $_POST['salary'];
    $bonus   =$_POST['bonus'];
    $comp_share = $_POST['comp_share'];
    $free_allowance = $_POST['free_allowance'];
    $act_allowance = $_POST['act_allowance'];
    $living_cost = $_POST['living_cost'];
    $social_bonus = $_POST['social_bonus'];
    $move_allowance = $_POST['move_allowance'];
    $other_allowance = $_POST['other_allowance'];
    $efforts = $_POST['efforts'];
    $monthly_grant = $_POST['monthly_grant'];
    $good_bonus = $_POST['good_bonus'];
    $total_earn = $_POST['total_earn'];
    $work_share = $_POST['work_share'];
    $service = $_POST['service'];
    $advance = $_POST['advance'];
    $comp_loan = $_POST['comp_loan'];
    $service_advance = $_POST['service_advance'];
    $service_loan = $_POST['service_loan'];
    $stamp = $_POST['stamp'];
    $tax = $_POST['tax'];
    $previous_taxes = $_POST['previous_taxes'];
    $debets = $_POST['debets'];
    $absence = $_POST['absence'];
    $penalties = $_POST['penalties'];
    $deductions = $_POST['deductions'];
    $net = $_POST['net'];
    $rupdate = R::load('permanentemployee', $id);
    $rupdate->name= $name;
    $rupdate->month = $month;
    $rupdate->salary = $salary;
    $rupdate->bonus = $bonus;
    $rupdate->comp_share = $comp_share;
    $rupdate->free_allowance = $free_allowance;
    $rupdate->act_allowance = $act_allowance;
    $rupdate->living_cost = $living_cost;
    $rupdate->social_bonus = $social_bonus;
    $rupdate->move_allowance = $move_allowance;
    $rupdate->other_allowance = $other_allowance;
    $rupdate->efforts = $efforts;
    $rupdate->monthly_grant = $monthly_grant;
    $rupdate->good_bonus = $good_bonus;
    $rupdate->total_earn = $total_earn;
    $rupdate->work_share = $work_share;
    $rupdate->service = $service;
    $rupdate->advance = $advance;
    $rupdate->comp_loan = $comp_loan;
    $rupdate->service_advance = $service_advance;
    $rupdate->service_loan = $service_loan;
    $rupdate->stamp = $stamp;
    $rupdate->tax = $tax;
    $rupdate->previous_taxes = $previous_taxes;
    $rupdate->debets = $debets;
    $rupdate->absence = $absence;
    $rupdate->penalties = $penalties;
    $rupdate->deductions = $deductions;
    $rupdate->net = $net;
    $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('permanentemployee', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}


function addRewardsByMonthExcel() {
    global $today;
    $userId = $_SESSION['userid'];
    
    if (!isset($_FILES['permanentemployeesheet'])) return false;
    $selectedMonth = isset($_POST['month']) ? (int)$_POST['month'] : 0;
    $excelfileName = uploadnew('permanentemployeesheet', false, 0, 0, 'permanentemployee', 7);
    $inputFileName = "../upload/permanentemployee/" . $excelfileName;

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

        
        for ($row = 3; $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) {
                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('permanentemployee', 'name = ? AND month = ? AND isdel = 0', [$employee->id, $selectedMonth]);
                
                if (!$pay) {
                    $pay = R::dispense('permanentemployee');
                }

             $pay->name   = (int)$employee->id;
                $pay->month  = (int)$selectedMonth;
                $pay->salary       =(float) $sheet->getCell('C' . $row)->getCalculatedValue(); 
                $pay->bonus   = (float) $sheet->getCell('D' . $row)->getCalculatedValue(); 
                $pay->comp_share  = (float) $sheet->getCell('E' . $row)->getCalculatedValue(); 
                $pay->free_allowance     = (float) $sheet->getCell('F' . $row)->getCalculatedValue(); 
                $pay->act_allowance   = (float) $sheet->getCell('G' . $row)->getCalculatedValue(); 
                $pay->living_cost      = (float) $sheet->getCell('H' . $row)->getCalculatedValue(); 
                $pay->social_bonus      = (float) $sheet->getCell('I' . $row)->getCalculatedValue(); 
                $pay->move_allowance         = (float) $sheet->getCell('J' . $row)->getCalculatedValue(); 
                $pay->other_allowance        = (float) $sheet->getCell('K' . $row)->getCalculatedValue();
                $pay->efforts        = (float) $sheet->getCell('L' . $row)->getCalculatedValue();
                $pay->monthly_grant        = (float) $sheet->getCell('M' . $row)->getCalculatedValue();
                $pay->good_bonus        = (float) $sheet->getCell('N' . $row)->getCalculatedValue();
                $pay->total_earn        = (float) $sheet->getCell('O' . $row)->getCalculatedValue();
                $pay->work_share        = (float) $sheet->getCell('P' . $row)->getCalculatedValue();
                $pay->service        = (float) $sheet->getCell('R' . $row)->getCalculatedValue();
                $pay->advance        = (float) $sheet->getCell('S' . $row)->getCalculatedValue();
                $pay->comp_loan        = (float) $sheet->getCell('T' . $row)->getCalculatedValue();
                $pay->service_advance        = (float) $sheet->getCell('U' . $row)->getCalculatedValue();
                $pay->service_loan        = (float) $sheet->getCell('V' . $row)->getCalculatedValue();
                $pay->stamp        = (float) $sheet->getCell('W' . $row)->getCalculatedValue();
                $pay->tax        = (float) $sheet->getCell('X' . $row)->getCalculatedValue();
                $pay->previous_taxes        = (float) $sheet->getCell('Y' . $row)->getCalculatedValue();
                $pay->debets        = (float) $sheet->getCell('Z' . $row)->getCalculatedValue();
                $pay->absence        = (float) $sheet->getCell('AA' . $row)->getCalculatedValue();
                $pay->penalties        = (float) $sheet->getCell('AB' . $row)->getCalculatedValue();
                $pay->deductions        = (float) $sheet->getCell('AC' . $row)->getCalculatedValue();
                $pay->net        = (float) $sheet->getCell('AD' . $row)->getCalculatedValue();
                $pay->sys_date = date("Y-m-d H:i:s");
                $pay->userid   = $userId;
                $pay->isdel    = 0;
                
                R::store($pay);
                $count++;
            }
        }
        return $count; 

    } catch (Exception $e) { 
        die('خطأ في معالجة الملف: ' . $e->getMessage()); 
    }
}
 