<?php
session_start();
require_once __DIR__ . "/../config/db.php";

/* =======================================================
   PHPMailer Setup
=========================================================*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/../vendor/PHPMailer/src/Exception.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/../vendor/PHPMailer/src/SMTP.php';

/* =======================================================
   1️⃣ AUTHORIZATION CHECK (Only Logged-in Admins Allowed)
=========================================================*/
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== "admin") {
    $_SESSION['add_staff_error'] = "Unauthorized access. Only admins can deactivate users.";
    header("Location: ../settings.php");
    exit();
}

/* =======================================================
   2️⃣ SANITIZE INPUTS
=========================================================*/
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$reason = isset($_GET['reason']) ? trim($_GET['reason']) : '';

/* =======================================================
   3️⃣ SAFETY CHECK: Prevent Admin From Deactivating Themselves
=========================================================*/
if ($id === intval($_SESSION['user_id'])) {
    $_SESSION['add_staff_error'] = "Security protection: You cannot deactivate your own admin account.";
    header("Location: ../settings.php");
    exit();
}

/* =======================================================
   4️⃣ FETCH TARGET USER DETAILS BEFORE DEACTIVATION
=========================================================*/
$target_name = '';
$target_email = '';

if ($id > 0 && $reason !== '') {
    $userStmt = mysqli_prepare($conn, "SELECT full_name, email FROM users WHERE id = ? AND is_deleted = 0");
    mysqli_stmt_bind_param($userStmt, "i", $id);
    mysqli_stmt_execute($userStmt);
    $userResult = mysqli_fetch_assoc(mysqli_stmt_get_result($userStmt));

    if ($userResult) {
        $target_name = $userResult['full_name'];
        $target_email = $userResult['email'];
    } else {
        $_SESSION['add_staff_error'] = "Deactivation failed: User not found or already inactive.";
        header("Location: ../settings.php");
        exit();
    }
} else {
    $_SESSION['add_staff_error'] = "Deactivation failed: Invalid User ID or missing reason statement.";
    header("Location: ../settings.php");
    exit();
}

/* =======================================================
   5️⃣ EXECUTE SOFT DELETE (UPDATE FLAG & LOG REASON)
=========================================================*/
$stmt = mysqli_prepare($conn, "UPDATE users SET is_deleted = 1, delete_reason = ? WHERE id = ?");
mysqli_stmt_bind_param($stmt, "si", $reason, $id);

if (mysqli_stmt_execute($stmt)) {
    
    /* =======================================================
       6️⃣ SEND DEACTIVATION NOTIFICATION EMAIL
    =========================================================*/
    try {
        $mail = new PHPMailer(true);

        /* SMTP SETTINGS */
        $mail->isSMTP();
        $mail->Host       = 'mail.priorisys.com';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'support@qrcare.priorisys.com';
        $mail->Password   = 'Hifzhan2017';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port       = 587;

        /* XAMPP / LOCAL HOST COMPATIBILITY */
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true
            ]
        ];

        /* EMAIL ROUTING DETAILS */
        $mail->setFrom('support@qrcare.priorisys.com', 'QRCareTrack');
        $mail->addAddress($target_email, $target_name);
        $mail->isHTML(true);
        $mail->Subject = 'Account Deactivation Notice - QRCareTrack';

        /* HTML EMAIL TEMPLATE */
        $mail->Body = "
        <div style='font-family: Segoe UI, sans-serif; padding: 20px; max-width: 600px; border: 1px solid #e0e0e0; border-radius: 8px;'>
            <h2 style='color: #e74c3c;'>Account Deactivation Notice</h2>
            <p>Hello <strong>{$target_name}</strong>,</p>
            <p>This email is to notify you that your account on the <strong>QRCareTrack System</strong> has been deactivated by the system administrator.</p>
            
            <div style='background-color: #f8f9fa; padding: 15px; border-left: 4px solid #e74c3c; margin: 20px 0;'>
                <strong>Reason for Deactivation:</strong><br>
                <span style='color: #555; font-style: italic;'>\"" . htmlspecialchars($reason) . "\"</span>
            </div>

            <p>Consequently, you will no longer be able to log in or access your dashboard data records.</p>
            <p>If you believe this action is a mistake, please contact your administrative manager directly.</p>
            <br>
            <p>Regards,<br><strong>QRCareTrack System Management</strong></p>
        </div>";

        /* TEXT-ONLY FALLBACK FOR OLDER EMAIL CLIENTS */
        $mail->AltBody = "Account Deactivation Notice\n\nHello {$target_name},\n\nThis email is to notify you that your account on the QRCareTrack System has been deactivated by the administrator.\n\nReason for Deactivation:\n\"{$reason}\"\n\nYou will no longer be able to log in to the system.\n\nRegards,\nQRCareTrack System Management";

        $mail->send();
        $_SESSION['add_staff_success'] = "User account has been deactivated successfully, and a notification email has been sent.";

    } catch (Exception $e) {
        // If the email fails, we still consider the database update a success but warn the admin
        $_SESSION['add_staff_warning'] = "User account was deactivated successfully, but the system failed to send the notification email.";
    }

} else {
    $_SESSION['add_staff_error'] = "Database error: Failed to update user deactivation status.";
}

/* =======================================================
   7️⃣ REDIRECT BACK
=========================================================*/
header("Location: ../settings.php");
exit();