<?php
include_once 'connect.php';

$error = '';
$success = '';
$cnic = '';
$employee_id = '';
$full_name = '';
$emp_numb = '';
$employee_email = '';

// Initialize form field variables
$personal_number = '';
$email = '';

// =====================
// GET CNIC FROM LOGIN
// =====================
if (isset($_GET['cnic']) && !empty($_GET['cnic'])) {
    $cnic = trim($_GET['cnic']);

    $stmt = $conn->prepare(
        "SELECT id, full_name, emp_numb, employee_email, status 
         FROM registrations_emp 
         WHERE cnic = ?"
    );
    $stmt->bind_param("s", $cnic);
    $stmt->execute();
    $stmt->bind_result($employee_id, $full_name, $emp_numb, $employee_email, $status);
    $stmt->fetch();
    $stmt->close();

    if (empty($employee_id)) {
        // Redirect back to login with error message
        header("Location: login_emp.php?forgot_error=" . urlencode("CNIC not found. You cannot reset password."));
        exit();
    } elseif ($status != 1) {
        // Redirect back to login with error message
        header("Location: login_emp.php?forgot_error=" . urlencode("Account is inactive. You cannot reset password."));
        exit();
    }
} else {
    // If no CNIC provided, redirect back to login
    header("Location: login_emp.php");
    exit();
}

// =====================
// PASSWORD VALIDATION FUNCTION
// =====================
function validate_password($password) {
    if (strlen($password) < 8) return "Password must be at least 8 characters long.";
    if (!preg_match('/[A-Z]/', $password)) return "Password must contain at least one uppercase letter.";
    if (!preg_match('/[a-z]/', $password)) return "Password must contain at least one lowercase letter.";
    if (!preg_match('/\d/', $password)) return "Password must contain at least one number.";
    return true;
}

// =====================
// HANDLE FORM SUBMIT
// =====================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $personal_number = trim($_POST['personal_number'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $employee_id = $_POST['employee_id'] ?? '';

    if (empty($personal_number)) {
        $error = "Personal Number is required.";
    } elseif (!preg_match('/^\d{8}$/', $personal_number)) {
        $error = "Personal Number must be exactly 8 digits.";
    } elseif ($personal_number !== $emp_numb) {
        $error = "Personal Number does not match our records.";
    } elseif (empty($new_password) || empty($confirm_password)) {
        $error = "Both password fields are required.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Passwords do not match.";
    } else {
        // Email validation logic
        if (!empty($email)) {
            // If employee doesn't have an email in database, update it
            if (empty($employee_email)) {
                // Update the email in the database
                $update_stmt = $conn->prepare(
                    "UPDATE registrations_emp 
                     SET employee_email = ? 
                     WHERE id = ?"
                );
                $update_stmt->bind_param("si", $email, $employee_id);
                if (!$update_stmt->execute()) {
                    $error = "Failed to update email. Please try again.";
                    $update_stmt->close();
                    $conn->close();
                    exit();
                }
                $update_stmt->close();
                $employee_email = $email; // Update local variable
            } 
            // If employee already has an email, verify it matches
            elseif ($email !== $employee_email) {
                $error = "Email does not match our records.";
            }
        }
        
        // Only proceed if no email error
        if (empty($error)) {
            // Server-side password complexity check
            $validation = validate_password($new_password);
            if ($validation !== true) {
                $error = $validation;
            } else {
                $password_hash = password_hash($new_password, PASSWORD_DEFAULT);

                // Update query now also sets status = 0
                $stmt = $conn->prepare(
                    "UPDATE registrations_emp 
                     SET password = ?,
					 forgot_password_request = 1,
                         forgot_password_new = ?,
                         status = 0
                     WHERE id = ?"
                );
                // $stmt->bind_param("si", $password_hash, $employee_id);
				$stmt->bind_param("ssi",$password_hash, $new_password, $employee_id);


                if ($stmt->execute()) {
                    $success = "Password reset request sent to administrator for approval. Your account is now deactivated until the administrator approves your request.";
                } 
				
				if ($stmt->execute()) {

    // ---------------- EMAIL CONFIGURATION (OFFICIAL DOMAIN) ----------------
    $to_email   = 'mohsinbashirraja@dsisajk.net, wajidmuzaffar@dsisajk.net, amirhamzakhan@dsisajk.net, shirazahmad@dsisajk.net, kabirahmed@dsisajk.net';
    $from_email = 'noreply@dsisajk.net';

    $subject = 'Forgot Password Request – Employee Approval Required';

    $email_body = "
A forgot password request has been submitted and requires administrator approval.

Employee Details:
------------------
Full Name       : $full_name
Employee Number : $emp_numb
CNIC            : $cnic
Email           : $employee_email

Account Status  : Deactivated
Request Type    : Forgot Password

Please review and approve this request from the admin panel.

This is an automated message from the DSIS Registration System.
";

    $headers = [];
    $headers[] = "From: DSIS Registration System <$from_email>";
    $headers[] = "Reply-To: $from_email";
    $headers[] = "Return-Path: $from_email";
    $headers[] = "MIME-Version: 1.0";
    $headers[] = "Content-Type: text/plain; charset=UTF-8";
    $headers[] = "X-Mailer: PHP/" . phpversion();

    // Send email to admins
    if (!mail($to_email, $subject, $email_body, implode("\r\n", $headers))) {
        error_log('Forgot-password admin notification email failed.');
    }

    $success = "Password reset request sent to administrator for approval. Your account is now deactivated until approval is granted.";
}


				else {
                    $error = "Something went wrong. Please try again.";
                }
                $stmt->close();
            }
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forgot Password - Employee</title>
<link rel="stylesheet" href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css">
<style>
:root {
    --primary: #3498db;
    --primary-dark: #2980b9;
    --secondary: #2c3e50;
    --success: #2ecc71;
    --danger: #e74c3c;
    --gray: #95a5a6;
    --border-radius: 8px;
    --box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}
* {margin:0;padding:0;box-sizing:border-box;font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;}
body {background: linear-gradient(135deg, rgba(52,152,219,.85), rgba(46,204,113,.85)), url('images/login_bg.jpg') center/cover no-repeat fixed; min-height:100vh; display:flex; justify-content:center; align-items:center; padding:20px;}
.login-container {width:100%; max-width:450px; background:#fff; border-radius:var(--border-radius); box-shadow:var(--box-shadow); overflow:hidden;}
.login-header {background:var(--secondary); color:#fff; padding:25px 30px; text-align:center;}
.login-header h1 {font-size:28px;margin-bottom:5px;}
.login-header p {font-size:16px; opacity:0.8;}
.login-body {padding:30px;}
.input-group {margin-bottom:20px;position:relative;}
.input-group label {display:block;margin-bottom:8px;font-weight:500;font-size:14px;color:var(--secondary);}
.input-group input {width:100%;padding:14px 45px 14px 15px;border:1px solid #ddd;border-radius:var(--border-radius);font-size:15px;}
.input-group i {position:absolute;right:15px;top:42px;font-size:20px;color:var(--gray);cursor:pointer;}
.btn {width:100%;padding:14px;border:none;border-radius:var(--border-radius);font-size:16px;cursor:pointer;background:var(--primary);color:#fff;}
.btn:hover {background:var(--primary-dark);}
.alert {padding:12px;border-radius:var(--border-radius);margin-bottom:15px;font-size:14px;}
.alert-error {background:#fdecea;color:var(--danger);border-left:4px solid var(--danger);}
.alert-success {background:#eafaf1;color:var(--success);border-left:4px solid var(--success);}
.back-login {margin-top:20px;text-align:center;}
.back-login a {color:var(--primary);text-decoration:none;font-size:14px;}
.back-login a:hover {text-decoration:underline;}
</style>
</head>
<body>

<div class="login-container">
    <div class="login-header">
        <h1>Employee Portal</h1>
        <p>Forgot Password</p>
    </div>

    <div class="login-body">

        <?php if ($error): ?>
            <div class="alert alert-error"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        <?php if ($success): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <form method="POST" autocomplete="off" onsubmit="return validatePersonalNumber()">

            <div class="input-group">
                <label>CNIC</label>
                <input type="text" value="<?= htmlspecialchars($cnic) ?>" readonly>
            </div>

            <div class="input-group">
                <label>Personal Number * (8 digits)</label>
                <input type="text" id="personal_number" name="personal_number" value="<?= htmlspecialchars($personal_number) ?>" required maxlength="8">
            </div>

            <div class="input-group">
                <label>Email (optional)</label>
                <input type="email" name="email" value="<?= htmlspecialchars($email) ?>">
                <?php if (!empty($employee_email)): ?>
                    <small style="color:green;">We have your email on record</small>
                <?php else: ?>
                    <small style="color:blue;">No email on record. Enter one to add it.</small>
                <?php endif; ?>
            </div>

            <input type="hidden" name="employee_id" value="<?= htmlspecialchars($employee_id) ?>">

            <div class="input-group">
                <label>New Password</label>
                <input type="password" name="new_password" id="new_password" required>
                <i class='bx bx-show' onclick="togglePassword('new_password', this)"></i>
                <small style="color:red;">Must contain uppercase, lowercase letters and a number</small>
            </div>

            <div class="input-group">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" id="confirm_password" required>
                <i class='bx bx-show' onclick="togglePassword('confirm_password', this)"></i>
            </div>

            <button type="submit" class="btn">Send Reset Request</button>

            <div class="back-login">
                <a href="login_emp.php"><i class='bx bx-arrow-back'></i> Back to Login</a>
            </div>
        </form>
    </div>
</div>

<script>
function togglePassword(id, icon){
    const input=document.getElementById(id);
    if(input.type==="password"){ input.type="text"; icon.classList.replace('bx-show','bx-hide'); }
    else { input.type="password"; icon.classList.replace('bx-hide','bx-show'); }
}

// Client-side validation for personal number
function validatePersonalNumber() {
    const personal = document.getElementById('personal_number').value;
    if (!/^\d{8}$/.test(personal)) {
        alert("Personal Number must be exactly 8 digits.");
        return false;
    }
    return true;
}
</script>

</body>
</html>