<?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['file_msg'] ="";

    $error = 0 ;
   

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

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

        $filePath = $location . $cust_id. '.' . $ext[1];
        $new_name =  $cust_id. '.' . $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->update((int)$cust_id,$_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);
}