<?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");
}
if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $year = $_GET['year'];
    $employee_id = $_GET['employee_id'];

    $showData = R::getAll("SELECT * FROM representationallowances WHERE year = ? AND isdel=0", [$year]);

    if (empty($showData)) {
        exit;
    }

    $smarty->assign('showData', $showData);
    $smarty->display("representationallowancesview/table_rows.html"); 
    exit; 
}


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("representationallowancesview/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") {

    $year = isset($_REQUEST['year']) ? (int)$_REQUEST['year'] : 0;
    $employee_id = isset($_REQUEST['employee_id']) ? (int)$_REQUEST['employee_id'] : 0;

    $employees = R::getAll("
        SELECT id, name 
        FROM employeesdetails 
        WHERE isdel = 0
        ORDER BY name ASC
    ");
   
    if ($year > 0) {
        $sql = "SELECT di.*, u.employeename, d.name AS employee_real_name
        FROM representationallowances di
        LEFT JOIN user u ON di.userid = u.userid 
        LEFT JOIN employeesdetails d ON di.employee_id = d.id 
        WHERE di.isdel = 0   AND di.year = ?";
        $showData = R::getAll($sql, [$year]);
    } else {
        $showData = []; 
    }
    $smarty->assign('employees', $employees);
    $smarty->assign('showData', $showData);
     $smarty->assign('currentYear', $year);
    $smarty->assign('currentEmployee', $employee_id);
    
    if (isset($_GET['ajax'])&& $_GET['ajax'] == 1) {
        $smarty->display("representationallowancesview/table_rows.html"); 
        exit;
    } else {
        $smarty->display("representationallowancesview/show.html");
        exit; 
        };

}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 = [
            'present_allowance','add1','move_allowance',
            'value','exe1','exe2','exe3','exe4','stamp',
            'total_deductions','net_allowance',
            'other_additions','other_discounts'
        ];

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

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

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

       
        $pay->$column = floatval($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 {

        if (!isset($_FILES['representationallowancessheet']) || empty($_FILES['representationallowancessheet']['tmp_name'])) {
            throw new Exception("لم يتم رفع ملف");
        }
        //$employeeId = isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0;
        $selectedYear = isset($_POST['year']) ? (int)$_POST['year'] : 0;
        $filePath = $_FILES['representationallowancessheet']['tmp_name'];

     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
  ================================ */
function add() {
   
    $name = $_POST['name'];
    $year = $_POST['year'];   
    $add1 = $_POST['add1'];  
    $present_allowance   =$_POST['present_allowance'];
    $move_allowance = $_POST['move_allowance'];
    $value = $_POST['value'];
    $exe1 = $_POST['exe1'];
    $exe2 = $_POST['exe2'];
    $exe3 = $_POST['exe3'];
    $exe4 = $_POST['exe4'];
    $stamp = $_POST['stamp'];
    $total_deductions = $_POST['total_deductions'];
    $net_allowance = $_POST['net_allowance'];
    $other_additions = $_POST['other_additions'];
    $other_discounts = $_POST['other_discounts']; 
    $rdispense = R::dispense('representationallowances');
    $rdispense->employee_name= $name;
    $rdispense->year = $year;
    $rdispense->add1 = $add1;
    $rdispense->present_allowance = $present_allowance;
    $rdispense->move_allowance = $move_allowance;
    $rdispense->value = $value;
    $rdispense->exe1 = $exe1;
    $rdispense->exe2 = $exe2;
    $rdispense->exe3 = $exe3;
    $rdispense->exe4 = $exe4;
    $rdispense->stamp = $stamp;
    $rdispense->total_deductions = $total_deductions;
    $rdispense->net_allowance = $net_allowance;
    $rdispense->other_additions = $other_additions;
    $rdispense->other_discounts = $other_discounts;
    $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'];
    $year = $_POST['year'];   
    $add1 = $_POST['add1'];  
    $present_allowance   =$_POST['present_allowance'];
    $move_allowance = $_POST['move_allowance'];
    $value = $_POST['value'];
    $exe1 = $_POST['exe1'];
    $exe2 = $_POST['exe2'];
    $exe3 = $_POST['exe3'];
    $exe4 = $_POST['exe4'];
    $stamp = $_POST['stamp'];
    $total_deductions = $_POST['total_deductions'];
    $net_allowance = $_POST['net_allowance'];
    $other_additions = $_POST['other_additions'];
    $other_discounts = $_POST['other_discounts']; 
    $rupdate = R::load('representationallowances', $id);
    $rupdate->employee_name= $name;
    $rupdate->year = $year;
    $rupdate->add1 = $add1;
    $rupdate->present_allowance = $present_allowance;
    $rupdate->move_allowance = $move_allowance;
    $rupdate->value = $value;
    $rupdate->exe1 = $exe1;
    $rupdate->exe2 = $exe2;
    $rupdate->exe3 = $exe3;
    $rupdate->exe4 = $exe4;
    $rupdate->stamp = $stamp;
    $rupdate->total_deductions = $total_deductions;
    $rupdate->net_allowance = $net_allowance;
    $rupdate->other_additions = $other_additions;
    $rupdate->other_discounts = $other_discounts;
    $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('representationallowances', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}

function addRewardsByMonthExcel() {
    global $today;
    $userId = $_SESSION['userid'];
    
    if (!isset($_FILES['representationallowancessheet'])) return false;
    $selectedYear = isset($_POST['year']) ? (int)$_POST['year'] : date("Y");
    $excelfileName = uploadnew('representationallowancessheet', false, 0, 0, 'representationallowances', 7);
    $inputFileName = "../upload/representationallowances/" . $excelfileName;

    try {
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        $sheet = $objPHPExcel->setActiveSheetIndex(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) {
                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('representationallowances', 'name = ? AND year = ? AND isdel = 0', [$employee->id, $selectedYear]);
                
                if (!$pay) {
                    $pay = R::dispense('representationallowances');
                }

                $pay->employee_name = $rawName;
                $pay->employee_id = $employee ? (int)$employee->id : 0;   
                $pay->year        = (int)$selectedYear; 
                $pay->add1      =(float) $sheet->getCell('D' . $row)->getCalculatedValue();
                $pay->present_allowance    = (float) $sheet->getCell('F' . $row)->getCalculatedValue();
                $pay->move_allowance  =(float) $sheet->getCell('H' . $row)->getCalculatedValue();
                $pay->value  =(float) $sheet->getCell('J' . $row)->getCalculatedValue();
                $pay->exe1  =(float) $sheet->getCell('L' . $row)->getCalculatedValue();
                $pay->exe2  =(float) $sheet->getCell('N' . $row)->getCalculatedValue();
                $pay->exe3  =(float) $sheet->getCell('P' . $row)->getCalculatedValue();
                $pay->exe4  =(float) $sheet->getCell('R' . $row)->getCalculatedValue();
                $pay->stamp  =(float) $sheet->getCell('T' . $row)->getCalculatedValue();
                $pay->total_deductions  =(float) $sheet->getCell('V' . $row)->getCalculatedValue();
                $pay->net_allowance  =(float) $sheet->getCell('X' . $row)->getCalculatedValue();
                $pay->other_additions    = 0;
                $pay->other_discounts     = 0;
                $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()); 
    }
}
 