<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "include/config.php";
include "../color.php";

// Initialize variables
$message = '';
$message_type = 'info';
$token = $_GET['token'] ?? '';
$valid_token = false;
$staff_id = null;

// Check if token exists and is valid
if (!empty($token)) {
    $current_time = date('Y-m-d H:i:s');
    $query = "SELECT * FROM password_reset_staff 
              WHERE token = ? AND expires_at > ? AND used = 0 
              LIMIT 1";
    
    $stmt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, "ss", $token, $current_time);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    
    if ($row = mysqli_fetch_assoc($result)) {
        $valid_token = true;
        $staff_id = $row['staff_id'];
    }
    mysqli_stmt_close($stmt);
}

// Handle password reset form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $new_password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $token = $_POST['token'] ?? '';
    
    // Validate passwords
    if (empty($new_password) || empty($confirm_password)) {
        $message = "Please fill in all password fields";
        $message_type = 'danger';
    } elseif (strlen($new_password) < 6) {
        $message = "Password must be at least 6 characters long";
        $message_type = 'danger';
    } elseif ($new_password !== $confirm_password) {
        $message = "Passwords do not match";
        $message_type = 'danger';
    } else {
        // Verify token again
        $current_time = date('Y-m-d H:i:s');
        $query = "SELECT * FROM password_reset_staff 
                  WHERE token = ? AND expires_at > ? AND used = 0 
                  LIMIT 1";
        
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, "ss", $token, $current_time);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        
        if ($row = mysqli_fetch_assoc($result)) {
            $staff_id = $row['staff_id'];
            
            // Hash the new password
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            // Update staff password
            $update_query = "UPDATE staff SET pass = ? WHERE id = ?";
            $update_stmt = mysqli_prepare($conn, $update_query);
            mysqli_stmt_bind_param($update_stmt, "si", $hashed_password, $staff_id);
            
            if (mysqli_stmt_execute($update_stmt)) {
                // Mark token as used
                $mark_used = "UPDATE password_reset_staff SET used = 1 WHERE token = ?";
                $used_stmt = mysqli_prepare($conn, $mark_used);
                mysqli_stmt_bind_param($used_stmt, "s", $token);
                mysqli_stmt_execute($used_stmt);
                mysqli_stmt_close($used_stmt);
                
                $message = "Password reset successfully! Redirecting to login...";
                $message_type = 'success';
                $valid_token = false;
                
                // Redirect to login after 3 seconds
                header("Refresh: 3; url=login.php");
            } else {
                $message = "Failed to update password. Please try again.";
                $message_type = 'danger';
            }
            mysqli_stmt_close($update_stmt);
        } else {
            $message = "Invalid or expired reset token. Please request a new reset link.";
            $message_type = 'danger';
            $valid_token = false;
        }
        mysqli_stmt_close($stmt);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Login | Secure Access</title>
    
    <!-- Bootstrap 5 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Favicon -->
    <link rel="icon" type="image/x-icon" href="logo.png">

    <style>
        :root {
            --primary: <?php echo $primary; ?>;
            --primary-dark: #3a56d7;
            --text-dark: #2d3748;
            --text-light: #718096;
            --shadow: 0 10px 30px rgba(0,0,0,0.08);
            --shadow-hover: 0 15px 40px rgba(0,0,0,0.12);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            --success-bg: #d1fae5;
            --success-text: #065f46;
            --danger-bg: #fee2e2;
            --danger-text: #991b1b;
            --info-bg: #dbeafe;
            --info-text: #1e40af;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Josefin Sans", sans-serif;
            color: var(--text-dark);
            min-height: 100vh;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }

        /* Background decorative elements */
        body::before {
            content: '';
            position: absolute;
            width: 300px;
            height: 300px;
            border-radius: 50%;
            background: linear-gradient(135deg, rgba(74, 108, 247, 0.1) 0%, rgba(74, 108, 247, 0.05) 100%);
            top: -150px;
            right: -150px;
            z-index: 0;
        }

        body::after {
            content: '';
            position: absolute;
            width: 200px;
            height: 200px;
            border-radius: 50%;
            background: linear-gradient(135deg, rgba(74, 108, 247, 0.08) 0%, rgba(74, 108, 247, 0.03) 100%);
            bottom: -100px;
            left: -100px;
            z-index: 0;
        }

        .reset-container {
            width: 100%;
            max-width: 420px;
            position: relative;
            z-index: 1;
        }

        .reset-card {
            background: white;
            border-radius: 20px;
            padding: 40px 35px;
            box-shadow: var(--shadow);
            transition: var(--transition);
            border: 1px solid rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
        }

        .reset-card:hover {
            box-shadow: var(--shadow-hover);
            transform: translateY(-5px);
        }

        .logo-container {
            text-align: center;
            margin-bottom: 30px;
        }

        .logo-circle {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background: var(--primary);
            margin: 0 auto 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 8px 20px rgba(74, 108, 247, 0.3);
            position: relative;
            overflow: hidden;
        }

        .logo-circle img {
            width: 60px;
            filter: brightness(0) invert(1);
            position: relative;
            z-index: 2;
        }

        .reset-title {
            text-align: center;
            margin-bottom: 30px;
            color: var(--text-dark);
            font-weight: 700;
            font-size: 1.75rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .reset-title i {
            color: var(--primary);
            font-size: 1.5rem;
        }

        .form-group {
            margin-bottom: 20px;
            position: relative;
        }

        .form-control {
            border-radius: 12px;
            padding: 14px 20px;
            border: 2px solid #e2e8f0;
            background: #f8fafc;
            color: var(--text-dark);
            font-size: 15px;
            transition: var(--transition);
            font-weight: 500;
        }

        .form-control:focus {
            border-color: var(--primary);
            background: white;
            box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
            outline: none;
        }

        .form-control::placeholder {
            color: #a0aec0;
            font-weight: 400;
        }

        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #a0aec0;
            cursor: pointer;
            padding: 5px;
        }

        .password-toggle:hover {
            color: var(--primary);
        }

        .btn-reset {
            width: 100%;
            padding: 14px;
            border-radius: 12px;
            border: none;
            font-weight: 600;
            font-size: 16px;
            background: var(--primary);
            color: white;
            transition: var(--transition);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            letter-spacing: 0.5px;
        }

        .btn-reset:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(74, 108, 247, 0.3);
        }

        .btn-reset:active {
            transform: translateY(0);
        }

        .btn-reset:disabled {
            background: #cbd5e0;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .links {
            margin-top: 25px;
            text-align: center;
            padding-top: 25px;
            border-top: 1px solid #e2e8f0;
        }

        .links a {
            color: var(--primary);
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            gap: 5px;
            margin: 0 10px;
        }

        .links a:hover {
            color: var(--primary-dark);
            text-decoration: underline;
        }

        .alert {
            border-radius: 12px;
            border: none;
            padding: 12px 16px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 500;
            animation: fadeIn 0.6s ease-out;
        }

        .alert-success {
            background-color: #d1fae5;
            color: #065f46;
            border-left: 4px solid #10b981;
        }

        .alert-danger {
            background-color: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }

        .alert-info {
            background-color: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #3b82f6;
        }

        .alert i {
            margin-right: 10px;
        }

        .loading-spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .reset-card {
            animation: fadeIn 0.6s ease-out;
        }

        /* Input label effect */
        .input-label {
            position: absolute;
            left: 15px;
            top: -8px;
            background: white;
            padding: 0 8px;
            font-size: 12px;
            color: var(--primary);
            font-weight: 600;
            opacity: 0;
            transition: var(--transition);
        }

        .form-control:focus + .input-label {
            opacity: 1;
        }

        /* Password requirements */
        .password-req {
            background: rgba(74, 108, 247, 0.05);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid var(--primary);
        }

        .password-req h6 {
            color: var(--primary);
            font-weight: 600;
            margin-bottom: 10px;
            font-size: 14px;
        }

        .password-req ul {
            list-style: none;
            padding-left: 0;
            margin-bottom: 0;
        }

        .password-req li {
            color: var(--text-light);
            font-size: 13px;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .password-req li i {
            color: var(--primary);
            font-size: 12px;
        }

        /* Responsive Design */
        @media (max-width: 576px) {
            .reset-card {
                padding: 30px 25px;
            }
            
            .logo-circle {
                width: 80px;
                height: 80px;
            }
            
            .logo-circle img {
                width: 50px;
            }
            
            body {
                padding: 15px;
            }
            
            body::before,
            body::after {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-card">
            <div class="logo-container">
                <div class="logo-circle">
                    <img src="logo.png" alt="Company Logo">
                </div>
                <h1 class="reset-title">
                    <i class="fas fa-lock"></i> Set New Password
                </h1>
            </div>

            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php 
                        $icon = '';
                        if ($message_type == 'success') $icon = 'fas fa-check-circle';
                        elseif ($message_type == 'danger') $icon = 'fas fa-exclamation-circle';
                        else $icon = 'fas fa-info-circle';
                    ?>
                    <i class="<?php echo $icon; ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            <?php endif; ?>

            <?php if (!$valid_token && empty($_POST)): ?>
                <!-- Invalid/Expired Token Message -->
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <span>Invalid or expired reset link. Please request a new password reset.</span>
                </div>
                
                <div class="links">
                    <a href="login.php">
                        <i class="fas fa-arrow-left"></i> Back to Login
                    </a>
                    <a href="forgot_password.php">
                        <i class="fas fa-key"></i> Request New Reset Link
                    </a>
                </div>
                
            <?php elseif ($valid_token): ?>
                <!-- Password Reset Form -->
                <div class="password-req">
                    <h6>Password Requirements:</h6>
                    <ul>
                        <li><i class="fas fa-check"></i> At least 6 characters long</li>
                        <li><i class="fas fa-check"></i> Use a combination of letters and numbers</li>
                        <li><i class="fas fa-check"></i> Avoid common passwords</li>
                    </ul>
                </div>
                
                <form method="POST" id="resetForm">
                    <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">
                    
                    <div class="form-group">
                        <input type="password" 
                               name="password" 
                               id="password"
                               class="form-control" 
                               placeholder="New Password"
                               required
                               autocomplete="new-password"
                               minlength="6">
                        <span class="input-label">New Password</span>
                        <