<?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 reactivate users.";
    header("Location: ../settings.php");
    exit();
}

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

/* =======================================================
   3️⃣ FETCH TARGET USER DETAILS BEFORE ACTIVATION
=========================================================*/
$target_name = '';
$target_email = '';

if ($id > 0) {
    $userStmt = mysqli_prepare($conn, "SELECT full_name, email FROM users WHERE id = ? AND is_deleted = 1");
    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'] = "Reactivation failed: User not found or account is already active.";
        header("Location: ../settings.php");
        exit();
    }
} else {
    $_SESSION['add_staff_error'] = "Reactivation failed: Invalid User ID selection.";
    header("Location: ../settings.php");
    exit();
}

/* =======================================================
   4️⃣ EXECUTE ACTIVATION (RESTORE STATUS FLAGS)
=========================================================*/
// Switch is_deleted back to 0 and clear the old reason log string
$stmt = mysqli_prepare($conn, "UPDATE users SET is_deleted = 0, delete_reason = NULL WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $id);

if (mysqli_stmt_execute($stmt)) {
    
    /* =======================================================
       5️⃣ SEND ACTIVATION 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 Reactivation 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: #2ecc71;'>Account Reactivated</h2>
            <p>Hello <strong>{$target_name}</strong>,</p>
            <p>Great news! Your account on the <strong>QRCareTrack System</strong> has been successfully reactivated by the system administrator.</p>
            
            <p>Your access rights and profile record histories are fully restored. You can now use your original registration credentials to sign back into your dashboard.</p>
            
            <div style='margin: 25px 0 15px 0;'>
                <a href='https://qrcare.priorisys.com/' style='background-color: #2ecc71; color: white; padding: 10px 20px; text-decoration: none; border-radius: 4px; font-weight: bold;'>Log In to Your Dashboard</a>
            </div>
            <br>
            <p>Regards,<br><strong>QRCareTrack System Management</strong></p>
        </div>";

        /* TEXT-ONLY FALLBACK FOR OLDER EMAIL CLIENTS */
        $mail->AltBody = "Account Reactivation Notice\n\nHello {$target_name},\n\nYour account on the QRCareTrack System has been reactivated by the administrator. You can now log back into your dashboard using your existing credentials.\n\nRegards,\nQRCareTrack System Management";

        $mail->send();
        $_SESSION['add_staff_success'] = "User account has been successfully reactivated, and a confirmation 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 reactivated successfully, but the system failed to send the notification email.";
    }

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

/* =======================================================
   6️⃣ REDIRECT BACK TO SETTINGS
=========================================================*/
header("Location: ../settings.php");
exit();
?>