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

if (isset($_POST['getadmin']) && $_POST['getadmin'] === '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
        ";

        $admins['current'] = fetchDataWithJoins($sql, ['layer' => 'admin']);
        $adminslotinfo = fetchData('dealer_slots', []);
        $admins['invited'] = fetchDataWithJoins($sql2, ['role' => 'admin']);

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

            foreach ($admins['current'] as &$admin) {
                $adminId = $admin['id'];
                if (isset($slotsMap[$adminId])) {
                    $admin['slots_avail'] = $slotsMap[$adminId]['slots_avail'];
                    $admin['slots_used'] = $slotsMap[$adminId]['slots_used'];
                } else {
                    $admin['slots_avail'] = 0;
                    $admin['slots_used'] = 0;
                }
            }
        }

        echo json_encode($admins);
    
    } 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['updateadmin'])) {
    try {

        $admins = fetchData('users', ['layer' => 'admin', 'id' => $_POST['userid']]);
        $slots = fetchData('dealer_slots', ['dealer_id' => $_POST['userid']]);
        $admins[0]['slots_avail'] = $slots[0]['slots_avail'];
        $admins[0]['slots_used'] = $slots[0]['slots_used'];

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

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

    if ($_SESSION['layer'] === 'super_admin') {
        try {
            $updateData = [
                'company_name' => $_POST['companyname'],
                'firstname' => $_POST['aFname'],
                'lastname' => $_POST['aLname'],
                'email' => $_POST['email']
            ];

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

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

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

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

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

    try {

        $message = handleInvitation($coname, $email, $role, $slots, 'Admin');
        
        if ($message) {
            
            $_SESSION['alert'] = [
                "message" => "Admin has been added successfully!",
                "type" => "success"
            ]; 
            
        } else {

            $_SESSION['alert'] = [
                "message" => "Failed to add New Admin. Please try again.",
                "type" => "danger"
            ];
        }

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

    } catch (Exception $e) {

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

if (isset($_POST['resendInvite'])) {
    if (!currentUserHasAccess($pdo, 'admin_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=admin_setup");
    }
    exit();
}
