<?php
// header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

// session_start();
if (session_status() === PHP_SESSION_NONE) session_start();
include '../../helper_functions/data_request.php';
include '../../../db.php';
include '../../auth/auth_functions.php';
include 'qr_code_template_functions.php';

if (!isset($_SESSION['userid'])) {
    sendJsonResponse(401, ["error" => "Unauthorized to access. Please login"]);
    exit;
}

try {
    if (isset($_POST['addQrCode'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $_POST['CreatedBy'] = $_SESSION['userid'];
        if (!isset($_POST['property_id'])) {
            sendJsonResponse(400, ["error" => "Property is not selected"]);
            exit;
        }
        $keys = ['type', 'phone_number', 'templateId', 'CreatedBy', 'property_id'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('qr_code', $data);
        if ($response == false) {
            sendJsonResponse(500, ["error" => "Could not add qr code"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'qr_code',
            $response['id']??null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Qr code added',
            'high',
            'Qr Code'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['deleteQrCodeById'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }

        $data = deleteData('qr_code', 'id', $_POST['id']);
        $response = $data;
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not delete qr code"]);
            exit;
        }
        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'qr_code',
            $_POST['id']??null,
            $_SESSION["email"]??null,
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Qr code deleted',
            'high',
            'Qr Code'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['getQRCodeData'])) {

        $_POST['property_id'] = $_POST['property_id'] ?? $_SESSION['property_id'] ?? null;
        if (!isset($_POST['property_id'])) {
            sendJsonResponse(400, ["error" => "Property is not selected"]);
            exit;
        }

        $sql = "SELECT qr_code.id AS id,qr_code.imageData,qr_code.qr_image ,qr_code.hasOrdered,qr_code.phone_number, qr_code.url, qr_code.email, qr_code.CreatedBy, qr_code.createdAt, qr_code.updatedAt, qr_code.status, qr_code.description, qr_code.type, qr_code.templateId, qr_code_templates.id AS template_id, qr_code_templates.templateName, qr_code_templates.templateHtml, qr_code_templates.position_ring_color, qr_code_templates.position_center_color, qr_code_templates.position_module_color, qr_code_templates.frameType, qr_code_templates.CreatedBy AS templateCreatedBy, qr_code_templates.createdAt AS templateCreatedAt, qr_code_templates.updatedAt AS templateUpdatedAt FROM qr_code LEFT JOIN qr_code_templates ON qr_code.templateId = qr_code_templates.id WHERE qr_code.property_id = :property_id AND qr_code.CreatedBy = :userid";

        // $params = ['property_id' => $_POST['property_id']];
        $params = [
            'property_id' => $_POST['property_id'],
            'userid' => $_SESSION['userid']
        ];

        $response = fetchDataWithJoins($sql, $params);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not fetch Qr Codes"]);
            exit;
        }

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['DataGetById'])) {
        $response = fetchDataWithId('qr_code', $_POST['id']);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not fetch Qr Code with Id " . $_POST['id']]);
            exit;
        }

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['editQrCode'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        // Get existing QR code data
        $existingData = fetchDataWithId('qr_code', $_POST['id']);
        if (!$existingData) {
            sendJsonResponse(500, ["error" => "QR code not found"]);
            exit;
        }

        // Handle QR code image upload if new image is provided
        if (isset($_FILES['qr_code_image']) && $_FILES['qr_code_image']['error'] == 0) {
            if (!empty($existingData['qr_image'])) {
                deleteSingleImageFromAllImages($existingData['qr_image']);
            }
            
            $isUploaded = uploadToAllImages('qr_code_image', $_POST['property_id']);
            if($isUploaded['success']){
                $_POST['qr_image'] = $isUploaded['image_path'];
            } else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }

        $keys = ['phone_number', 'templateId', 'qr_image'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        
        $updateSuccess = updateTable('qr_code', $data, $where, $params);
        if ($updateSuccess === false) {
            sendJsonResponse(500, ["error" => "Could not update the QR code"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'qr_code',
            $_POST['id'],
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'QR code updated with new image',
            'high',
            'Qr Code'
        );
        
        sendJsonResponse(200, [
            "success" => true,
            "data" => $updateSuccess,
            "message" => "QR code updated successfully"
        ]);
        exit;
    }

    if (isset($_POST['AddEditedImage'])) {

        
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        
       
        if (!isset($_POST['download_original'])) {
            $isUploaded = uploadToAllImages('imageData', $_POST['property_id']);
            if($isUploaded['success']){
                $_POST['imageData'] = $isUploaded['image_path'];
            } else {
                sendJsonResponse(500, ["upload_error" => $isUploaded['error']]);
                exit;
            }
        }
        $keys = ['imageData'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('qr_code', $data, $where, $params);
        $response = $updateSuccess;
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not update the qr code with" . $_POST['id']]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'qr_code',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Qr code template edited image added',
            'high',
            'Qr Code'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response,
            "imageData" => $_POST['imageData']
        ]);
        exit;
    }

    // Handle saving QR code with image
    if (isset($_POST['saveQrCode'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        if (isset($_FILES['qr_code_image']) && $_FILES['qr_code_image']['error'] == 0) {
            $isUploaded = uploadToAllImages('qr_code_image', $_POST['property_id']);
            if($isUploaded['success']){
                $_POST['qr_image'] = $isUploaded['image_path'];
            } else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        } else {
            sendJsonResponse(500, ["error" => "QR code image is required"]);
            exit;
        }

        $_POST['CreatedBy'] = $_SESSION['userid'];
        $keys = ['phone_number', 'templateId', 'CreatedBy', 'property_id', 'qr_image'];
        $data = array_intersect_key($_POST, array_flip($keys));
        
        $response = insertData('qr_code', $data);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not save QR code"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'qr_code',
            $response['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'QR code saved with image',
            'high',
            'Qr Code'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response,
            "message" => "QR code saved successfully"
        ]);
        exit;
    }

    //================== templates Requests ==================
    if (isset($_POST['addTemplate'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        if (!empty($_POST['templateName'])) {
            $defaultNameFound = fetchDataSingle('qr_code_templates', ['templateName' => $_POST['templateName'],"is_default"=>1]);
            if (!empty($defaultNameFound)) {
                sendJsonResponse(500, ["error" => "Default template is present with this name"]);
                exit;
            }
            $isAlreadyAddedNameFound = fetchDataSingle('qr_code_templates', ['templateName' => $_POST['templateName'],"property_id"=>$_POST['property_id']]);
            if (!empty($isAlreadyAddedNameFound)) {
                sendJsonResponse(500, ["error" => "Template is already there"]);
                exit;
            }
        }

        if (isset($_FILES['template_image']) && $_FILES['template_image']['error'] == 0) {
            $isUploaded = uploadToAllImages('template_image', $_POST['property_id']);
            if($isUploaded['success']){
                $_POST['template_image']=$isUploaded['image_path'];
            }else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }

        $keys = ['templateName','template_image','property_id' ,'position_ring_color','page_size', 'position_center_color', 'position_module_color', 'frameType', 'templateHtml'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('qr_code_templates', $data);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not add the qr code template"]);
            exit;
        }
        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'qr_code_templates',
            $response['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'New qr template added',
            'high',
            'Qr Code'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['editQrTemplate'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        $dataById = fetchDataSingle('qr_code_templates', ['id' => $_POST['id']]);
        if (empty($dataById)) {
            sendJsonResponse(500, ["error" => 'Data not found against the id ' . $_POST['id']]);
            exit;
        }

        if (isset($_FILES['template_image']) && $_FILES['template_image']['error'] == 0) {
            $message = deleteSingleImageFromAllImages($dataById['template_image']);
            $isUploaded = uploadToAllImages('template_image', $_POST['property_id']);
            if ($isUploaded['success']) {
                $_POST['template_image']=$isUploaded['image_path'];
            } else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }

        $keys = ['templateName','template_image', 'position_ring_color','page_size', 'position_center_color', 'position_module_color', 'frameType', 'templateHtml'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $where = 'id = :id';
        $params = ['id' => $_POST['id']];
        $updateSuccess = updateTable('qr_code_templates', $data, $where, $params);
        $response = $updateSuccess;


        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not update the qr template " . $_POST['id']]);
            exit;
        }
        createAuditLog(
            $_SESSION["userid"],
            'Update',
            'qr_code_templates',
            $_POST['id'] ?? null,
            $_SESSION["email"] ?? null,
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Qr template updated',
            'high',
            'Qr Code'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }

    // getting the Qr templates
    if (isset($_POST['getQRTemplates'])) {
        $response = fetchData('qr_code_templates');
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not get the qr templates"]);
            exit;
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['getTemplateById'])) {
        $response = fetchDataWithId('qr_code_templates', $_POST['id']);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not fetch Qr Code with Id " . $_POST['id']]);
            exit;
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['deleteTemplateById'])) {
        if (!currentUserHasAccess($pdo, 'property_builder', 'delete')){
            sendJsonResponse(500, ["error" => "You are not authorized to delete"]);
            exit;
        }
        $templateToDelete = fetchDataWithId('qr_code_templates', $_POST['id']);
        if (!isset($templateToDelete['id'])) {
            sendJsonResponse(500, ["error" => "Could not fetch Qr Code template with Id"]);
            exit;
        } else if ($templateToDelete['is_default'] == 1) {
            sendJsonResponse(500, ["error" => "You cannot delete the default qr code templates"]);
            exit;
        }
        $response = deleteData('qr_code_templates', 'id', $_POST['id']);
        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'qr_code_templates',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Qr template deleted',
            'high',
            'Qr Code'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
    if (isset($_POST['DataGetByIdWithJoin'])) {
        $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

        if ($id <= 0) {
            sendJsonResponse(400, ["error" => "Invalid id"]);
            exit;
        }

        // SQL query to fetch data with the specified ID using the join
        $sql = "SELECT qr_code.id AS id, qr_code.phone_number,qr_code.qr_image, qr_code.url, qr_code.email, qr_code.CreatedBy, qr_code.createdAt, qr_code.updatedAt, qr_code.status, qr_code.description, qr_code.type, qr_code.templateId, qr_code_templates.id AS template_id, qr_code_templates.templateName, qr_code_templates.templateHtml, qr_code_templates.position_ring_color, qr_code_templates.page_size ,qr_code_templates.position_center_color, qr_code_templates.position_module_color, qr_code_templates.frameType, qr_code_templates.CreatedBy AS templateCreatedBy, qr_code_templates.createdAt AS templateCreatedAt, qr_code_templates.updatedAt AS templateUpdatedAt FROM qr_code LEFT JOIN qr_code_templates ON qr_code.templateId = qr_code_templates.id WHERE qr_code.id = :id;";
        // Fetch the data using the global function
        $response = fetchDataWithJoins($sql, [':id' =>  $id]);
        if (empty($response)) {
            sendJsonResponse(404, ["error" => "No QR Code found with Id " . $_POST['id']]);
            exit;
        }
        $responseObject = (object) $response[0];

        sendJsonResponse(200, [
            "success" => true,
            "data" => $responseObject
        ]);
        exit;
    }

    if(isset($_POST['save_edited_template'])){

        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }

        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }
        if (isset($_FILES['template_image']) && $_FILES['template_image']['error'] == 0) {
            $isUploaded = uploadToAllImages('template_image', $_POST['property_id']);
            if($isUploaded['success']){
                $_POST['template_image']=$isUploaded['image_path'];
            }else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }
        $isAlreadyAddedNameFound = fetchDataSingle('qr_code_templates', ['templateName' => $_POST['templateName'],'property_id' => $_POST['property_id'],'is_default' => null]);
        if (empty($isAlreadyAddedNameFound)) {
            $keys = ['templateName','template_image','property_id' ,'position_ring_color','page_size', 'position_center_color', 'position_module_color', 'frameType', 'templateHtml'];
            $data = array_intersect_key($_POST, array_flip($keys));
            $response = insertData('qr_code_templates', $data);
            sendJsonResponse(200, [
                "success" => true,
                "data" => "Data has added successfully"
            ]);
            exit;
        }else {
            if($isAlreadyAddedNameFound["template_image"]){
                $message = deleteSingleImageFromAllImages($isAlreadyAddedNameFound["template_image"]);
            }
            $keys = ['templateName','template_image', 'position_ring_color','page_size', 'position_center_color', 'position_module_color', 'frameType', 'templateHtml'];
            $data = array_intersect_key($_POST, array_flip($keys));
            $where = 'id = :id';
            $params = ['id' => $isAlreadyAddedNameFound['id']];
            $updateSuccess = updateTable('qr_code_templates', $data, $where, $params);
            $response = $updateSuccess;
            sendJsonResponse(200, [
                "success" => true,
                "data" => $response
            ]);
            exit;
        }

    }

    if(isset($_POST['save_edited_qr_code_template'])){
        if (!currentUserHasAccess($pdo, 'property_builder', 'write')){
            sendJsonResponse(500, ["error" => "You are not authorized to write"]);
            exit;
        }
        if (empty($_POST['property_id'])) $_POST['property_id'] = $_SESSION['property'];
        if (empty($_POST['property_id'])) {
            sendJsonResponse(500, ["error" => 'Property id is missing']);
            exit;
        }

        if(!empty($_POST['previous_image_path'])){
            deleteSingleImageFromAllImages($_POST['previous_image_path']);
        }

        if (isset($_FILES['qr_code_template_image']) && $_FILES['qr_code_template_image']['error'] == 0) {                       
            $isUploaded = uploadToAllImages('qr_code_template_image', $_POST['property_id']);
            if($isUploaded['success']){
                sendJsonResponse(200, [
                    "success" => true,
                    "data" => $isUploaded['image_path']
                ]);
            } else {
                sendJsonResponse(500, ["error" => $isUploaded['error']]);
                exit;
            }
        }
        
        exit;

    }
    // vinyl Order

    if (isset($_POST['getVinylOrders'])) {
        $sql = "SELECT vinyl_printed_orders.id, vinyl_printed_orders.orderId, vinyl_printed_orders.type, vinyl_printed_orders.qrCodeId, vinyl_printed_orders.orderedAt, vinyl_printed_orders.orderBy, vinyl_printed_orders.status, vinyl_printed_orders.quantity, vinyl_printed_orders.size, vinyl_printed_orders.shippedAt, vinyl_printed_orders.shippingAddress, qr_code.phone_number 
        FROM vinyl_printed_orders 
        JOIN qr_code ON vinyl_printed_orders.qrCodeId = qr_code.id 
        WHERE vinyl_printed_orders.orderBy = :id;";

        // Fetch the data using the global function
        $response = fetchDataWithJoins($sql, [':id' => $_SESSION['userid']]);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not get vinyl orders"]);
            exit;
        }
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }

    if (isset($_POST['addVinylOrder'])) {
        if (isset($_SESSION['userid'])) {
            $_POST['orderBy'] = $_SESSION['userid'];
        }
        $keys = ['qrCodeId', 'qrCodeId', 'quantity', 'shippingAddress', 'type', 'orderBy', 'orderId', 'size'];
        $data = array_intersect_key($_POST, array_flip($keys));
        $response = insertData('vinyl_printed_orders', $data);
        $data2['hasOrdered'] = $_POST['orderId'];
        $where = 'id = :id';
        $params = ['id' => $_POST['qrCodeId']];
        $updateSuccess = updateTable('qr_code', $data2, $where, $params);
        if ($response === false) {
            sendJsonResponse(500, ["error" => "Could not add vinyl order"]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Create',
            'vinyl_printed_orders',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Order has created',
            'high',
            'Orders'
        );
        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }

    if (isset($_POST['deleteVinylOrder'])) {
        $response = deleteData('vinyl_printed_orders', 'id', $_POST['id']);
        $data2['hasOrdered'] = null;
        $where = 'id = :id';
        $params = ['id' => $_POST['qrCodeId']];
        $updateSuccess = updateTable('qr_code', $data2, $where, $params);
        if ($response === false) {
            sendJsonResponse(400, ["error" => "Could not update the qr code with " . $_POST['id']]);
            exit;
        }

        createAuditLog(
            $_SESSION["userid"],
            'Delete',
            'vinyl_printed_orders',
            $_POST['id'] ?? null,
            $_SESSION["email"],
            $_SESSION['property_id'] ?? null,
            null,
            null,
            'Order has been canceled',
            'high',
            'Orders'
        );

        sendJsonResponse(200, [
            "success" => true,
            "data" => $response
        ]);
        exit;
    }
} catch (\Throwable $th) {
    sendJsonResponse(500, ["error" => "Server error"]);
    exit;
}
