<?php


require_once __DIR__ . '/../magic/auth.php';

$auth = bdr_require_privilege(6, '../logout.php');
$user = $auth['user_id'];
$father = $auth['user_id'];
$branch = $auth['branch'];
$conn = $auth['conn'];
$db = $auth['conn'];

require_once("../magic/DataBase.php");
require_once("../magic/Customers.php");

$table = "customers";
$custmoer = new Customers($dataBase,$table);

function compressImage($sourcePath, $destinationPath, $quality = 50) {
    // Load the image
    $image = imagecreatefromjpeg($sourcePath);

    // Save the compressed image
    $result = imagejpeg($image, $destinationPath, $quality);

    // Free up memory
    imagedestroy($image);

    return $result ? $destinationPath : false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {


    $response["save_msg"] = "يوجد خطأ في بيانات الشركة";
    
    $response['idSA_msg'] ="";
    $response['cust_name_msg'] ="";
    $response['cust_vat_msg'] ="";
    $response['phone_msg'] ="";
    $response['phone2_msg'] ="";
    $response['w_phone_msg'] ="";
    $response['w_phone2_msg'] ="";
    $response['CityName_msg'] ="";
    $response['SubDivisionName_msg'] ="";
    $response['StreetName_msg'] ="";
    $response['BuildingNumber_msg'] ="";
    $response['PlotIdentification_msg'] ="";
    $response['PostalNumber_msg'] ="";
    $response['file_msg'] ="";

    $error = 0 ;
    if($custmoer->findIDSA((int) $_POST['idSA'])){
        $data = $custmoer->findIDSA($_POST['idSA']);
        $response['idSA_msg'] = " هوية ".$data['cust_name'];
        $error = $error+1;
    }
    if($custmoer->findCustVat($_POST['cust_vat'])){
        $data = $custmoer->findCustVat($_POST['cust_vat']);
        $response['cust_vat_msg'] = " رقم ضريبي  ".$data['cust_name'];
        $error = $error+1;
    }
    if($custmoer->findPhone((int) $_POST['phone'])){
        $data = $custmoer->findPhone($_POST['phone']);
        $response['phone_msg'] = " رقم تليفون ".$data['cust_name'] ;
        // $error = $error+1;
    }

if($error < 1 )
{
    $location = "../photo/customers/" ;
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {

        $file = $_FILES['file'];
        $ext = explode('.', $file["name"]);
        $photo_idSA = $_POST['idSA'];

        $filePath = $location . $photo_idSA. '.' . $ext[1];
        $new_name =  $photo_idSA. '.' . $ext[1];

        // Validate file type
        $allowedTypes = ['image/jpeg', 'application/pdf'];
        if (!in_array($file['type'], $allowedTypes)) {
            $response['file_msg'] = 'Invalid file type. Only JPG and PDF files are allowed.';
            $response['success'] = false;
        } else {
            if($file['type'] === 'application/pdf'){
                if (move_uploaded_file($file['tmp_name'], $filePath)) {
                    $response['success'] = true;
                    $response['file_msg'] = 'File uploaded successfully.';   
                }
             }else{
                $compressedFilePath = compressImage($file['tmp_name'], $filePath,40); // 75% quality
            }
        }
        $_POST['cust_photo'] = $new_name ;
    } else {
        $response['file_msg'] = 'يوجد خطأ في تحميل الملف او لا يوجد ملف للتحميل.';
        $_POST['cust_photo'] = "" ;
    }
   
    unset($_POST['file']); // Removes the file
    unset($_POST['action']);
    $_POST['father'] = $father ;
    $_POST['branch'] = $branch ;
    
        $success = $custmoer->insert($_POST);
        if($success){
            $response["success"] = true;
            $response["save_msg"] = "تم إضافة الشركة بنجاح";
        }else{
            $response['success'] = false;
            $response["save_msg"] = "يوجد خطأ في بيانات الشركة";
            }
    }
   
 header('Content-Type: application/json');
 echo json_encode($response);
}
// update
if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {


    // $response["save_msg"] = "يوجد خطأ في بيانات الشركة";
    $response["save_msg"] = '<div id="successAlert" class="alert alert-danger alert-dismissible fade show" role="alert">
    <strong>راجع من فضلك</strong> يوجد خطأ في بيانات الشركة
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div> ';
    
    $response['idSA_msg'] ="";
    $response['cust_name_msg'] ="";
    $response['cust_vat_msg'] ="";
    $response['phone_msg'] ="";
    $response['phone2_msg'] ="";
    $response['w_phone_msg'] ="";
    $response['w_phone2_msg'] ="";
    $response['CityName_msg'] ="";
    $response['SubDivisionName_msg'] ="";
    $response['StreetName_msg'] ="";
    $response['BuildingNumber_msg'] ="";
    $response['PlotIdentification_msg'] ="";
    $response['PostalNumber_msg'] ="";

    $error = 0 ;
    // Get the raw POST data
    $patchData = json_decode(file_get_contents("php://input"), true);

    if($custmoer->findIDSA((int)$patchData['idSA'])){
        $data = $custmoer->findIDSA((int) $patchData['idSA']);
       if( $data['cust_id'] != $patchData['cust_id']){

        $response['idSA_msg'] = " هوية ".$data['cust_name'];
        $error = $error+1;
    }
        
    }
    if($custmoer->findCustVat($patchData['cust_vat'])){
        $data = $custmoer->findCustVat($patchData['cust_vat']);
        if( $data['cust_id'] != $patchData['cust_id']){

        $response['cust_vat_msg'] = " رقم ضريبي  ".$data['cust_name'];
        $error = $error+1;

        }
    }
    if($custmoer->findPhone($patchData['phone'])){
        $data = $custmoer->findPhone($patchData['phone']);
        if( $data['cust_id'] != $patchData['cust_id']){

        $response['phone_msg'] = " رقم تليفون ".$data['cust_name'] ;
        // $error = $error+1;

        }
    }

if($error < 1 )
{
    $patchData['father'] = $father ;
    $patchData['branch'] = $branch ;
    $cust_id = $patchData['cust_id'];
    
        $success = $custmoer->update((int)$cust_id ,$patchData);
        if($success){
            $response["success"] = true;
            $response["save_msg"] = '<div id="successAlert" class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>تم التعديل بنجاح!</strong> لقد تم حفظ التغييرات التي قمت بها.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div> ';
        }else{
            $response['success'] = false;
            $response["save_msg"] = '<div id="successAlert" class="alert alert-danger alert-dismissible fade show" role="alert">
            <strong>راجع من فضلك</strong> يوجد خطأ في بيانات الشركة
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div> ';
            }
    }
   
 header('Content-Type: application/json');
 echo json_encode($response);
}

?>