<?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";
$customer = 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') {
   if( $_POST['action'] ==="new"){
$response["save_msg"] = "يوجد خطأ ";
    
    $response['idSA_msg'] ="";
    // $response['cust_name_msg'] ="";
    $response['phone_msg'] ="";
    // $response['phone2_msg'] ="";
    // $response['w_phone_msg'] ="";
    // $response['w_phone2_msg'] ="";
    // $response['address_msg'] ="";
    // $response['license_msg'] ="";
    // $response['file_msg'] ="";

    $error = 0 ;
    if($customer->findIDSA((int) $_POST['idSA'])){
        $data = $customer->findIDSA($_POST['idSA']);
        $response['idSA_msg'] = " هوية ".$data['cust_name'];
        $error = $error+1;
    }

    if($customer->findPhone((int) $_POST['phone'])){
        $data = $customer->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 = $customer->insertCustomer($_POST);
        if($success){
            $response["success"] = true;
            $response["save_msg"] = "تم إضافة عميل جديد";
        }else{
            $response['success'] = false;
            $response["save_msg"] = "يوجد خطأ في بيانات العميل";
            }
    }
   
   }
   else // update
    {
$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'] ="";

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

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

        $response['idSA_msg'] = " هوية ".$data['cust_name'];
        $error = $error+1;
    }
        
    }

    if($customer->findPhone((int) $_POST['phone'])){
        $data = $customer->findPhone((int) $_POST['phone']);
        if( $data['cust_id'] != $_POST['cust_id']){

        $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'] = 'يوجد خطأ في تحميل الملف او لا يوجد ملف للتحميل.';
         unset($_POST['cust_photo']);
    }
   
   unset($_POST['file']); // Removes the file
    $_POST['father'] = $father ;
    $_POST['branch'] = $branch ;
    $cust_id = $_POST['cust_id'];

    unset($_POST['action']);
    
        $success = $customer->update((int)$cust_id ,$_POST);
        if($success){
            $response["success"] = true;
            $response["save_msg"] = '<strong>تم التعديل بنجاح!</strong> لقد تم حفظ التغييرات التي قمت بها.';
        }else{
            $response['success'] = false;
            $response["save_msg"] = '<strong>راجع من فضلك</strong> يوجد خطأ في بيانات المستأجر';
            }
    }
   }

    
 header('Content-Type: application/json');
 echo json_encode($response);
}
// update
// if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {


    
   
//  header('Content-Type: application/json');
//  echo json_encode($response);
// }

?>