<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include '../../db.php';
include '../../shared/functionsinc.php';
include 'users_invitation.php';
include '../helper_functions/data_request.php';
include '../auth/auth_functions.php';

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST["submitnewadmins"])) {

    if (!currentUserHasAccess($pdo, 'users', 'write') && !in_array($_SESSION['layer'], ['super_admin', 'admin', 'dealer', 'sub_dealer'])) {

        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $firstname = trim($_POST['firstname']);
    $lastname = trim($_POST['lastname']);
    $email = filter_var($_POST['newemail'], FILTER_SANITIZE_EMAIL);
    $mobile = preg_replace('/\D/', '', $_POST['mobile']);
    $role = (int)$_POST['adminsList']; // 1 = Organization Admin, 2 = Sub-Dealer
    $password = password_hash(bin2hex(random_bytes(6)), PASSWORD_BCRYPT);
    $creator_type = "users";
    $custom = 0;
    $user_type = 'dealer_admins';

    if ($_SESSION['layer'] === 'sub_dealer') {
        $findDealer = fetchData('dealer_admins', ['id' => $_SESSION['userid']]);
        $dealer_assoc = $findDealer[0]['dealer_assoc'];
    }else {
        $dealer_assoc = $_SESSION['userid'];
    }

    if (empty($firstname) || empty($lastname) || empty($email) || empty($mobile) || $role === 0) {
        throw new Exception("All fields are required.");
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new Exception("Invalid email format.");
    }

    $adminsExist = emailExists($pdo, $email);
    if ($adminsExist) {
        throw new Exception("Email already exists.");
    }

    $layer = ($role === 1) ? 'organization admin' : 'sub_dealer';

    $inviteToken = sendInvitation($pdo, $email, $role, $custom, $dealer_assoc, $creator_type, $user_type, $firstname, NULL);
    
    if (!$inviteToken) {
        $_SESSION['alert'] = [
                "message" => "An Invitation is already present for this Email Address. Please try again.",
                "type" => "danger"
            ];
        header("location: ../../dashboard.php?tab=users");
        exit();
    }
    
    try {
        $pdo->beginTransaction();

        $adminData = [
            'firstname' => $firstname,
            'lastname' => $lastname,
            'email' => $email,
            'password' => $inviteToken,
            'layer' => $layer,
            'status' => 'not registered',
            'dealer_assoc' => $dealer_assoc
        ];
        $result = insertData('dealer_admins', $adminData);
        if (!$result) {
            throw new Exception("Failed to insert dealer admin.");
        }

        $dealer_admin_id = getLastInsertId();

        if($role == 1){
            $role_us = "Organization Admin";
        }
        else{
            $role_us = "Sub Dealer";
        }
        createAuditLog($_SESSION["userid"], "Added New " . $role_us, "dealer_admins", $dealer_admin_id, $_SESSION["email"]??null, $_SESSION['property'], null, $firstname . " " . $lastname, "Added new ". $role_us, "high", $role_us);
        
        $updateData = [
            'dealer_admin_id' => $dealer_admin_id
        ];
    
        $whereClause = 'email = :email';
        $whereParams = [
            'email' => $email
        ];
    
        $updateSuccess = updateTable('dealer_invitations', $updateData, $whereClause, $whereParams);

        if (!empty($_POST['organization_access'])) {
            $organizations = explode(",", $_POST['organization_access']);
            foreach ($organizations as $org_id) {
                $orgAccessData = [
                    'dealer_admin_id' => $dealer_admin_id,
                    'access_type' => 'organization',
                    'access_id' => $org_id,
                    'assigned_by' => $dealer_assoc
                ];
                insertData('dealer_admins_access', $orgAccessData);
            }
        }

        if (!empty($_POST['property_access'])) {
            $properties = explode(",", $_POST['property_access']);
            $firstPropertyId = $properties[0];
            foreach ($properties as $prop_id) {
                $propAccessData = [
                    'dealer_admin_id' => $dealer_admin_id,
                    'access_type' => 'property',
                    'access_id' => $prop_id,
                    'assigned_by' => $dealer_assoc
                ];
                insertData('dealer_admins_access', $propAccessData);
            }
        }

        $photoData = [
            'user_id' => $dealer_admin_id,
            'user_type' => $user_type,
            'property_id' => $firstPropertyId,
            'location' => '',
            'created_by' => $dealer_assoc,
            'creator_type' => $creator_type
        ];
        $photoInsertResult = insertData('profile_photo', $photoData);
        $lastPhotoInsertId = $photoInsertResult['id'];

        $adminDataDetails = [
            'dealer_admins_id' => $dealer_admin_id,
            'mobile_number' => $mobile,
            'role' => $role,
            'custom' => 0,
            'created_by' => $_SESSION['userid'],
            'creator_type' => $creator_type,
            'photo_loc' => $lastPhotoInsertId
        ];
        $result = insertData('dealer_admins_data', $adminDataDetails);
        if (!$result) {
            throw new Exception("Failed to insert dealer admin data.");
        }

        $pdo->commit();
        $_SESSION['alert'] = [
            "message" => "Admin User has been added successfully!",
            "type" => "success"
        ];
        header("location: ../../dashboard.php?tab=users");
        exit();
    } catch (Exception $e) {
        $pdo->rollBack();
        // echo "Failed to register: " . $e->getMessage();
        $_SESSION['alert'] = [
            "message" => "Failed to add Admin User. Please try again.",
            "type" => "danger"
        ];

        header("location: ../../dashboard.php?tab=users");
        exit();
    }
}

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

    if (!currentUserHasAccess($pdo, 'users', 'write') && !in_array($_SESSION['layer'], ['super_admin', 'admin', 'dealer', 'sub_dealer'])) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $combined = [];
    $orgadmins = fetchData('dealer_admins', ['deleted_at' => NULL, 'layer' => 'organization admin']) ?? [];

    if(!empty($orgadmins)){
        foreach ($orgadmins as &$orgadm) {   // <-- notice the &
            $orgadmindata = fetchDataSingle('dealer_admins_data', ['dealer_admins_id' => $orgadm['id']]);
            
            if (isset($orgadmindata['photo_loc'])) {
                $photoData = fetchData('profile_photo', ['id' => $orgadmindata['photo_loc']]);
                $orgadm['photo_loc'] = !empty($photoData) ? $photoData[0]['location'] : null;
            } else {
                $orgadm['photo_loc'] = "";
            }
        }
        unset($orgadm);
    }
    $combined['orgadmins'] = $orgadmins;
    
    $dealeradmins = fetchData('dealer_admins', ['deleted_at' => NULL, 'layer' => 'sub_dealer']) ?? [];

    if (!empty($dealeradmins)) {
        foreach ($dealeradmins as &$dealeradm) {   // <-- added &
            $dealeradmindata = fetchDataSingle('dealer_admins_data', ['dealer_admins_id' => $dealeradm['id']]);

            if (isset($dealeradmindata['photo_loc'])) {
                $photoDataDealer = fetchData('profile_photo', ['id' => $dealeradmindata['photo_loc']]);
                $dealeradm['photo_loc'] = !empty($photoDataDealer) ? $photoDataDealer[0]['location'] : null;
            } else {
                $dealeradm['photo_loc'] = "";
            }
        }
        unset($dealeradm);
    }
    $combined['dealeradmins'] = $dealeradmins;
    // Fetch audit trail logins for all dealer admins
    $auditTrailData = fetchData('audit_trail_login', []);
    $auditTrailMapping = [];

    foreach ($auditTrailData as $audit) {
        if ($audit['dealer_admin_id']) {
            $auditTrailMapping[$audit['dealer_admin_id']] = $audit['logged_time']; // Store the last logged time for each dealer admin
        }
    }

    $filtered = [
        'orgadmins' => !empty($combined['orgadmins']) ? array_map(fn($orgadmin) => [
            'id' => $orgadmin['id'] ?? null,
            'firstname' => $orgadmin['firstname'] ?? null, 
            'lastname' => $orgadmin['lastname'] ?? null, 
            'email' => $orgadmin['email'] ?? null,
            'layer' => $orgadmin['layer'] ?? null,
            'status' => $orgadmin['status'] ?? null,
            'dealer_assoc' => $orgadmin['dealer_assoc'] ?? null,
            'photo_loc' => $orgadmin['photo_loc'] ?? null,
            'last_logged_in' => $auditTrailMapping[$orgadmin['id']] ?? null // Attach last login time
        ], $combined['orgadmins']) : [],

        'dealeradmins' => !empty($combined['dealeradmins']) ? array_map(fn($dealeradmin) => [
            'id' => $dealeradmin['id'] ?? null,
            'firstname' => $dealeradmin['firstname'] ?? null, 
            'lastname' => $dealeradmin['lastname'] ?? null, 
            'email' => $dealeradmin['email'] ?? null,
            'layer' => $dealeradmin['layer'] ?? null,
            'status' => $dealeradmin['status'] ?? null,
            'dealer_assoc' => $dealeradmin['dealer_assoc'] ?? null,
            'photo_loc' => $dealeradmin['photo_loc'] ?? null,
            'last_logged_in' => $auditTrailMapping[$dealeradmin['id']] ?? null // Attach last login time
        ], $combined['dealeradmins']) : [],
    ];

    echo json_encode($filtered);
    exit();
}

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

    if (!currentUserHasAccess($pdo, 'users', 'write') && !in_array($_SESSION['layer'], ['super_admin', 'admin', 'dealer'])) {

        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $dealeradminsId = $_POST['dealeradminsid'];
    $dealeradminsData['user'] = fetchData('dealer_admins', ['id' => $dealeradminsId]);
    $dealeradminsData['data'] = fetchData('dealer_admins_data', ['dealer_admins_id' => $dealeradminsId]);
    $dealeradminsData['access'] = fetchData('dealer_admins_access', ['dealer_admin_id' => $dealeradminsId]);

    echo json_encode($dealeradminsData);
    exit();

}

if (isset($_POST['updateDealerAdmin'])) {
    if (!currentUserHasAccess($pdo, 'users', 'write') && !in_array($_SESSION['layer'], ['super_admin', 'admin', 'dealer'])) {
        echo json_encode(['error' => 'Access Denied']);
        exit();
    }

    $dealeradminsId = $_POST['idstore'];
    $firstname = trim($_POST['firstname']);
    $lastname = trim($_POST['lastname']);
    $mobile = trim(preg_replace('/\D/', '', $_POST['mobile']));

    if (empty($firstname) || empty($lastname)) {
        throw new Exception("All fields are required.");
    }

    $dealer_admin_o_data = fetchDataSingle('dealer_admins', ['id' => $dealeradminsId]);
    $dealer_admin_m_data = fetchDataSingle('dealer_admins_data', ['dealer_admins_id' => $dealeradminsId]);

    updateTable('dealer_admins', ['firstname' => $firstname, 'lastname' => $lastname], 'id = :id', ['id' => $dealeradminsId]);

    updateTable('dealer_admins_data', ['mobile_number' => $mobile], 'dealer_admins_id = :dealer_admins_id', ['dealer_admins_id' => $dealeradminsId]);

    if (isset($_POST["permissionsUpdated"]) && $_POST["permissionsUpdated"] === "true") {

        $existingPermissions = fetchData('dealer_admins_access', ['dealer_admin_id' => $dealeradminsId]);

        $existingOrgPermissions = [];
        $existingPropPermissions = [];

        foreach ($existingPermissions as $perm) {
            if ($perm['access_type'] === 'organization') {
                $existingOrgPermissions[] = $perm['access_id'];
            } elseif ($perm['access_type'] === 'property') {
                $existingPropPermissions[] = $perm['access_id'];
            }
        }

        $newOrgPermissions = isset($_POST["organization_access"]) && !empty($_POST["organization_access"]) ? explode(',', $_POST["organization_access"]) : [];
        $newPropPermissions = isset($_POST["property_access"]) && !empty($_POST["property_access"]) ? explode(',', $_POST["property_access"]) : [];

        $orgsToRemove = array_diff($existingOrgPermissions, $newOrgPermissions);
        $propsToRemove = array_diff($existingPropPermissions, $newPropPermissions);

        $stmt = $pdo->prepare("DELETE FROM dealer_admins_access WHERE dealer_admin_id = :dealer_admin_id AND access_id = :access_id AND access_type = :access_type");

        foreach ($orgsToRemove as $orgId) {
            $stmt->execute([
                'dealer_admin_id' => $dealeradminsId,
                'access_id' => $orgId,
                'access_type' => 'organization'
            ]);
        }

        foreach ($propsToRemove as $propId) {
            $stmt->execute([
                'dealer_admin_id' => $dealeradminsId,
                'access_id' => $propId,
                'access_type' => 'property'
            ]);
        }

        $orgsToAdd = array_diff($newOrgPermissions, $existingOrgPermissions);
        $propsToAdd = array_diff($newPropPermissions, $existingPropPermissions);

        foreach ($orgsToAdd as $orgId) {
            insertData('dealer_admins_access', [
                'dealer_admin_id' => $dealeradminsId,
                'access_id' => $orgId,
                'access_type' => 'organization',
                'assigned_by' => $_SESSION['userid']
            ]);
        }

        foreach ($propsToAdd as $propId) {
            insertData('dealer_admins_access', [
                'dealer_admin_id' => $dealeradminsId,
                'access_id' => $propId,
                'access_type' => 'property',
                'assigned_by' => $_SESSION['userid']
            ]);
        }
    }

    if(isset($dealer_admin_o_data['id']) && !empty($dealer_admin_o_data['id'])){
        if($dealer_admin_o_data['layer'] == "sub_dealer"){
            $layer_d = "sub dealer";
        }
        else{
            $layer_d = "organization admin";
        }

        if($dealer_admin_o_data['firstname'] != $firstname){
            createAuditLog($_SESSION["userid"], "Udated " . $layer_d . " First Name", "dealer_admins", $dealeradminsId, $_SESSION["email"]??null, null, $dealer_admin_o_data['firstname'], $firstname, "Udated " . $layer_d . " first name", "high", "dealer_admins");
        }
        if($dealer_admin_o_data['lastname'] != $lastname){
            createAuditLog($_SESSION["userid"], "Udated " . $layer_d . " Last Name", "dealer_admins", $dealeradminsId, $_SESSION["email"]??null, null, $dealer_admin_o_data['lastname'], $lastname, "Udated " . $layer_d . " last name", "high", "dealer_admins");
        }
        if($dealer_admin_m_data['mobile_number'] != $mobile){
            createAuditLog($_SESSION["userid"], "Udated " . $layer_d . " Mobile", "dealer_admins_data", $dealer_admin_m_data['id'], $_SESSION["email"]??null, null, $dealer_admin_m_data['mobile'], $mobile, "Udated " . $layer_d ." mobile", "high", "dealer_admins_data");
        }
    }

    $_SESSION['alert'] = [
        "message" => "Admin User has been Updated successfully!",
        "type" => "success"
    ];
    header("location: ../../dashboard.php?tab=users");
    exit();
}

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

    $adminToDelete = $_POST['id'];

    $whereClause = 'id = :id';
    $whereParams = ['id' => $adminToDelete];
    $admin_dealer_data = fetchDataSingle('dealer_admins', ['id' => $adminToDelete]);
    
    updateTable('dealer_admins', ['deleted_at' => date('Y-m-d H:i:s')], $whereClause, $whereParams);
    if($admin_dealer_data['layer'] == "sub_dealer"){
        $data_layer = "sub dealer";
    }
    else{
       $data_layer = "organization admin"; 
    }
    createAuditLog($_SESSION["userid"], "Deleted " . $data_layer, "dealer_admins", $adminToDelete, $_SESSION["email"]??null, $_SESSION['property'], $admin_dealer_data['firstname'] . " " . $admin_dealer_data['lastname'], date('Y-m-d H:i:s'), "Deleted " . $data_layer, "high", "Soft delete for " . $data_layer . " " . $admin_dealer_data['id'] . " in table dealer_admins");

    $whereClause = 'dealer_admins_id = :id';
    $whereParams = ['id' => $adminToDelete];
    updateTable('dealer_admins_data', ['deleted_at' => date('Y-m-d H:i:s')], $whereClause, $whereParams);

    deleteData('dealer_admins_access', 'dealer_admin_id', $adminToDelete);
    
    echo "Success";
    exit();
}

