<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once('../../db.php');
include '../../shared/functionsinc.php';
include '../auth/auth_functions.php';
include '../helper_functions/data_request.php';
require_once '../auth/send_invitation.php';

if (isset($_POST['getdealer']) && $_POST['getdealer'] === 'yes') {
    try {

        $sql = "
            SELECT u.id, u.company_name, CONCAT(u.firstname, ' ', u.lastname) AS name, u.layer, u.email, u.created_at AS created
            FROM users u
            WHERE u.layer = :layer
        ";
        // , deleted_at
        //  AND u.deleted_at IS NULL
        $sql2 = "
            SELECT id, company_name, email, role, dealer_slots, created_at
            FROM invitations
            WHERE role = :role
        ";
    
        $dealers['current'] = fetchDataWithJoins($sql, ['layer' => 'dealer']);
        $dealersslotinfo = fetchData('dealer_slots', []);
        $dealers['invited'] = fetchDataWithJoins($sql2, ['role' => 'dealer']);

        $slotsMap = [];
        foreach ($dealersslotinfo as $slot) {
            $slotsMap[$slot['dealer_id']] = [
                'slots_avail' => $slot['slots_avail'],
                'slots_used' => $slot['slots_used']
            ];
        }

        foreach ($dealers['current'] as &$dealer) {
            $dealerId = $dealer['id'];
            $dealer_logo = fetchDataSingle('users_data', ['user_id' => $dealerId]);
            $dealer['logo_loc'] = $dealer_logo['logo_loc'];
            if (isset($slotsMap[$dealerId])) {
                $dealer['slots_avail'] = $slotsMap[$dealerId]['slots_avail'];
                $dealer['slots_used'] = $slotsMap[$dealerId]['slots_used'];
            } else {
                $dealer['slots_avail'] = 0;
                $dealer['slots_used'] = 0;
            }
        }
    
        echo json_encode($dealers);
    
    } catch (Exception $e) {
        error_log("Error fetching dealers: " . $e->getMessage());
        echo json_encode(["error" => "Unable to fetch dealer data. Please try again later."]);
    }
}

if (isset($_POST['updatedealer']) && $_POST['getslots'] === 'yes') {
    try {

        $dealers = fetchData('users', ['layer' => 'dealer', 'id' => $_POST['userid']]);
        $dealer_data = fetchDataSingle('users_data', ['user_id' => $_POST['userid']]);
        $dSlots = fetchData('dealer_slots', ['dealer_id' => $_POST['userid']]);
        $dealers[0]['slots_avail'] = $dSlots[0]['slots_avail'];
        $dealers[0]['slots_used'] = $dSlots[0]['slots_used'];
        $dealers[0]['logo_loc'] = $dealer_data['logo_loc'];


        echo json_encode($dealers);
    } catch (Exception $e) {
        error_log("Error fetching dealers: " . $e->getMessage());
        echo json_encode(["error" => "Unable to fetch dealer data. Please try again later."]);
    }
}

if (isset($_POST["submit"]) && $_POST['submit'] === 'Update Dealer') {

    if ($_SESSION['layer'] === 'super_admin' || $_SESSION['layer'] === 'admin') {
        try {
            
            $dealer_data = fetchDataSingle('users', ['id' => $_POST['idstore'], 'layer' => 'dealer']);
            
            if (isset($_FILES['dealer_logo']) && $_FILES['dealer_logo']['error'] === UPLOAD_ERR_OK) {
                $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
                $fileMimeType = $_FILES['dealer_logo']['type'];

                if (!in_array($fileMimeType, $allowedMimeTypes)) {
                    throw new Exception('Invalid image type. Only JPG, PNG, and GIF are allowed.');
                }

                $maxFileSize = 4 * 1024 * 1024;
                if ($_FILES['dealer_logo']['size'] > $maxFileSize) {
                    return ["success" => false, "error" => "File size exceeds the 4MB limit."];
                }

                $targetDir = "../../../../data/profile_images/";
                $fileExtension = strtolower(pathinfo($_FILES['dealer_logo']['name'], PATHINFO_EXTENSION));
                $imageFileName = 'user_' . $_POST['idstore'] . '_profile_' . time() . '.' . $fileExtension;
                $targetFilePath = $targetDir . $imageFileName;

                if (move_uploaded_file($_FILES['dealer_logo']['tmp_name'], $targetFilePath)) {

                    chmod($targetFilePath, 0666);

                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                        shell_exec("icacls " . escapeshellarg($targetFilePath) . " /grant Everyone:F");
                    }
            
                    $logo_name = $imageFileName;

                    $row = fetchDataSingle('users_data', ['user_id' => $_POST['idstore']]);
                    
                    if ($row) {
                        deleteProfilePhotoForAdmins($_POST['idstore'], "1");

                        // Update the existing logo photo entry
                        $stmt = $pdo->prepare("UPDATE users_data SET logo_loc = :logo_loc WHERE user_id = :userId AND deleted_at IS NULL");
                        $stmt->execute([
                            ':logo_loc' => $logo_name,
                            ':userId' => $_POST['idstore']
                        ]);

                        createAuditLog($_SESSION["userid"], "Updated Dealer Logo", "users", $_POST['idstore'], $_SESSION["email"]??null, null, $row['logo_loc'], $logo_name, "Updated delaer logo", "high", "users");
                        
                    }

                } else {
                    throw new Exception("Failed to upload image.");
                }
            }

            $updateData = [
                'company_name' => $_POST['companyname'],
                'firstname' => $_POST['dFname'],
                'lastname' => $_POST['dLname'],
                'email' => $_POST['email']
            ];

            $whereClause = 'id = :id AND layer = :layer';
            $whereParams = [
                'id' => $_POST['idstore'],
                'layer' => 'dealer'
            ];

            $updateSuccess = updateTable('users', $updateData, $whereClause, $whereParams);

            if(isset($dealer_data['id']) && !empty($dealer_data['id'])){
                if($dealer_data['company_name'] != $_POST['companyname']){
                    createAuditLog($_SESSION["userid"], "Updated Dealer Company Name", "users", $_POST['idstore'], $_SESSION["email"]??null, null, $dealer_data['company_name'], $_POST['companyname'], "Updated delaer company name", "high", "users");
                }
                if($dealer_data['firstname'] != $_POST['dFname']){
                    createAuditLog($_SESSION["userid"], "Updated Dealer First Name", "users", $_POST['idstore'], $_SESSION["email"]??null, null, $dealer_data['firstname'], $_POST['dFname'], "Updated delaer first name", "high", "users");
                }
                if($dealer_data['lastname'] != $_POST['dLname']){
                    createAuditLog($_SESSION["userid"], "Updated Dealer Last Name", "users", $_POST['idstore'], $_SESSION["email"]??null, null, $dealer_data['lastname'], $_POST['dLname'], "Updated delaer last name", "high", "users");
                }
                if($dealer_data['email'] != $_POST['companyname']){
                    createAuditLog($_SESSION["userid"], "Updated Dealer Email", "users", $_POST['idstore'], $_SESSION["email"]??null, null, $dealer_data['email'], $_POST['email'], "Updated delaer email", "high", "users");
                }

            }

            if ($updateSuccess) {
                $_SESSION['alert'] = [
                    "message" => "Dealer has been updated successfully!",
                    "type" => "success"
                ];
            } else {
                $_SESSION['alert'] = [
                    "message" => "There was an error updating the dealer.",
                    "type" => "error"
                ];
            }
        } catch (Exception $e) {
            error_log("Error updating dealer: " . $e->getMessage());
            $_SESSION['alert'] = [
                "message" => "An error occurred while updating the dealer.",
                "type" => "error"
            ];
        }
    } else {
        $_SESSION['alert'] = [
            "message" => "Access Denied. Please check your login!",
            "type" => "danger"
        ];
    }

    if (!headers_sent()) {
        header("location: ../../dashboard.php?tab=dealer_setup");
    }
    exit();
}

if (isset($_POST['submitnewdealer'])) {
    $email = $_POST['email'];
    $role = 'dealer';
    $slots = $_POST['initialslots'];
    $coname = $_POST['companyname'];

    try {

        $message = handleInvitation($coname, $email, $role, $slots, 'Dealer');
        
        if ($message) {
            $invite_id = getLastInsertId();

            $_SESSION['alert'] = [
                "message" => "Dealer has been added successfully!",
                "type" => "success"
            ]; 
            createAuditLog($_SESSION["userid"], "Invite New Dealer", "invitations", $invite_id, $_SESSION["email"]??null, null, null, $email, "Invite new dealer", "high", "invitations");
        } else {

            $_SESSION['alert'] = [
                "message" => "Failed to add New Dealer. Please try again.",
                "type" => "danger"
            ];
        }
        if (!headers_sent()) {
            header("location: ../../dashboard.php?tab=dealer_setup");
        }
        exit();

    } catch (Exception $e) {

        $_SESSION['alert'] = [
            "message" => "An error occurred: " . $e->getMessage(),
            "type" => "danger"
        ];
        if (!headers_sent()) {
            header("location: ../../dashboard.php?tab=dealer_setup");
        }
        exit();
    }
}

if (isset($_POST['resendInvite'])) {
    if (!currentUserHasAccess($pdo, 'dealer_setup', 'read')) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $userid = isset($_POST['userid']) ? intval($_POST['userid']) : 0;
    $sendinvite = resendInvitation($userid);
    
    if ($sendinvite === 'Success') {
        $_SESSION['alert'] = [
            "message" => "The Invitation was Successfully Sent!",
            "type" => "success"
        ];

    }else {
        $_SESSION['alert'] = [
            "message" => "The Invitation Failed to Send. Please try again.",
            "type" => "danger"
        ];
    }
    if (!headers_sent()) {
        header("location: ../../dashboard.php?tab=dealer_setup");
    }
    exit();
}

if (isset($_POST['getbilling'])) {
    $billingData = fetchData('users_data', ['user_id' => $_POST['userid']]);
    $bData = json_encode($billingData);
    echo $bData;
    exit();
}

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

    $bconame = isset($_POST['bconame']) ? htmlspecialchars(trim($_POST['bconame'])) : '';
    $billingaddress = isset($_POST['billingaddress']) ? htmlspecialchars(trim($_POST['billingaddress'])) : '';
    $billingapt = isset($_POST['billingapt']) ? htmlspecialchars(trim($_POST['billingapt'])) : '';
    $billingcity = isset($_POST['billingcity']) ? htmlspecialchars(trim($_POST['billingcity'])) : '';
    $billingstate = isset($_POST['billingstate']) ? htmlspecialchars(trim($_POST['billingstate'])) : '';
    $billingzip = isset($_POST['billingzip']) ? htmlspecialchars(trim($_POST['billingzip'])) : '';
    $billingcontactphone = isset($_POST['billingcontactphone']) ? htmlspecialchars(trim(preg_replace('/\D/', '', $_POST['billingcontactphone']))) : '';
    $bidstore = $_POST['bidstore'];

    if (!$bidstore) {
        $_SESSION['alert'] = [
            "message" => "Invalid User ID.",
            "type" => "danger"
        ];
        if (!headers_sent()) {
            header("location: ../../dashboard.php?tab=dealer_setup");
        }
        exit();
    }

    $user_billing_data = fetchDataSingle('users_data', ['user_id' => $bidstore]);

    $billData = [
        'apartment' => $billingapt,
        'city' => $billingcity,
        'full_name' => $bconame,
        'phone_number' => $billingcontactphone,
        'postal_code' => $billingzip,
        'state' => $billingstate,
        'street_address' => $billingaddress
    ];

    $whereClause = 'user_id = :user_id';
    $whereParams = ['user_id' => $bidstore];

    $updateSuccess = updateTable('users_data', $billData, $whereClause, $whereParams);
    
    if(isset($user_billing_data['id']) && !empty($user_billing_data['id'])){
        if(empty($user_billing_data['full_name']) && empty($user_billing_data['street_address']) && empty($user_billing_data['apartment']) && empty($user_billing_data['city']) && empty($user_billing_data['state']) && empty($user_billing_data['postal_code']) && empty($user_billing_data['phone_number'])){
            createAuditLog($_SESSION["userid"], "Added Dealer Billing Info", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, null, json_encode($billData), "Added dealer billing info", "high", "Dealer billing info");
        }
        else{
            if($user_billing_data['apartment'] != $billingapt){
                createAuditLog($_SESSION["userid"], "Update Dealer Billing Apartment", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['apartment'], $billingapt, "Added dealer billing apartment", "high", "Dealer billing info");
            }

            if($user_billing_data['city'] != $billingcity){
                createAuditLog($_SESSION["userid"], "Update Dealer Billing City", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['city'], $billingcity, "Added dealer billing city", "high", "Dealer billing info");
            }

            if($user_billing_data['full_name'] != $bconame){
                createAuditLog($_SESSION["userid"], "Updated Dealer Billing Full Name", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['full_name'], $bconame, "Added dealer billing full name", "high", "Dealer billing info");
            }

            if($user_billing_data['phone_number'] != $billingcontactphone){
                createAuditLog($_SESSION["userid"], "update Dealer Billing Phone Number", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['phone_number'], $billingcontactphone, "Added dealer billing phone number", "high", "Dealer billing info");
            }

            if($user_billing_data['postal_code'] != $billingzip){
                createAuditLog($_SESSION["userid"], "updated Dealer Billing Postal Code", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['postal_code'], $billingzip, "Added dealer billing postal code", "high", "Dealer billing info");
            }

            if($user_billing_data['state'] != $billingstate){
                createAuditLog($_SESSION["userid"], "updated Dealer Billing State", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['state'], $billingstate, "Added dealer billing state", "high", "Dealer billing info");
            }

            if($user_billing_data['street_address'] != $billingaddress){
                createAuditLog($_SESSION["userid"], "updated Dealer Billing Street Address", "users_data", $user_billing_data['id'], $_SESSION["email"]??null, null, $user_billing_data['street_address'], $billingaddress, "Added dealer billing street address", "high", "Dealer billing info");
            }

        }
    }
    

    $_SESSION['alert'] = [
        "message" => $updateSuccess ? "Billing Information update success!" : "Failed to update Billing Information. Please try again.",
        "type" => $updateSuccess ? "success" : "danger"
    ];

    if (!headers_sent()) {
        header("location: ../../dashboard.php?tab=dealer_setup");
    }
    exit();
}
