<?php
////////////////////////////////////////////////////////////////////////////////////////
require_once("class.restframework.php");
require_once("class.saas.php");
///////////////////////////////////////////////////////////////////////////////////////
header('Content-Type: application/json');
///////////////////////////////////////////////////////////////
$upload_path = "../templates/default/images/";
// dirname(__DIR__) . 
///////////////////////////////////////////////////////////////////////////////////////
$restapi = new RestFrameWork();
$saas = new SaaS($restapi);
//////////////////////////////////////////////////////////////////////////////////////
$restapi->allow("post");
$auth = $restapi->Auth();
$companyid = $auth["company"];
////////////////////////////////////////////////////////////////////////////////////////
// $upload_path = $company->utils->joinPaths(__DIR__, $upload_path);
// Create directories if they don't exist
if (!file_exists($upload_path)) {
    mkdir($upload_path, 0777, true);
}
// echo json_encode($auth);
// return $upload_path;
/////////////////////////////////////////////
$company = $saas->company->getCompany($companyid);
$company_no = $company["company_no"];
$db_name = $company["db_name"];
/////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
$allowedLogoTypes = ['image/jpeg', 'image/png', 'image/gif'];
$allowedFaviconTypes = ['image/x-icon', 'image/png', 'image/vnd.microsoft.icon'];
//////////////////////////////////////////////////////////
$response = ['success' => false, 'message' => ''];
try {

    ////////////////////////////////////////////
    if (!isset($_POST["UploadType"]) || empty($_POST["UploadType"])) {
        throw new Exception('Upload type is required.');
    }
    ////////////////////////////////////////////
    $UploadType = trim($_POST["UploadType"]);
    // if ($UploadType == "logo" || $UploadType == "favicon") {
    //     throw new Exception('Upload type should either be logo or favicon');
    // }
    // Check if files were uploaded
    if (!isset($_FILES['Image'])) {
        throw new Exception('Upload image is required.');
    }
    ///////////////////////////////////////
    $ImageFile = $_FILES['Image'];
    // Validate logo
    if ($ImageFile['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Logo upload failed with error code: ' . $ImageFile['error']);
    }

    if ($UploadType == "logo") {
        // Check file types
        $logoType = mime_content_type($ImageFile['tmp_name']);
        if (!in_array($logoType, $allowedLogoTypes)) {
            throw new Exception('Invalid logo file type. Allowed: JPG, PNG, GIF.');
        }
    } else {
        $faviconType = mime_content_type($ImageFile['tmp_name']);
        if (!in_array($faviconType, $allowedFaviconTypes)) {
            throw new Exception('Invalid favicon file type. Allowed: ICO, PNG.');
        }
    }
    // Generate random filenames with original extensions
    $ImageExt = pathinfo($ImageFile['name'], PATHINFO_EXTENSION);
    if ($UploadType == "logo") {
        $ImageName = $company_no . '_' . $db_name . '_' . 'logo' . '.' . $ImageExt;
    } else {
        $ImageName = $company_no . '_' . $db_name . '_' . 'favicon' . '.' . $ImageExt;
    }

    // Move uploaded files to their directories
    $ImagePath = $upload_path . $ImageName;
    // delete file if it exits
    if (file_exists($ImagePath)) {
        unlink($ImagePath);
    }
    //////////////////////////////////////////////////////////////////////////
    if (!move_uploaded_file($ImageFile['tmp_name'], $ImagePath)) {
        throw new Exception('Failed to save logo file.');
    }
    ///////////////////////////////////////////////////////////
    if ($UploadType == "logo") {
        $saas->company->updateCompany([
            "logo" => $ImageName
        ], $companyid);
        $saas->CreateCompany($companyid);
    } else {
        $saas->company->updateCompany([
            "favicon" => $ImageName
        ], $companyid);
        $saas->CreateCompany($companyid);
    }
    //////////////////////////////////////////////////////////////
    $response['success'] = true;
    $response['message'] = $UploadType == "logo" ? 'Logo uploaded successfully.' : 'Favicon uploaded successfully.';
    $response['ImageName'] = $ImageName;
    $response['UploadType'] = $UploadType;
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}
echo $restapi->Response($response);
////////////////////////////////////////////////////////////////////////////
