<?php
require_once 'config.php';

if (isset($_SESSION['user_id'])) {
    header("Location: registration.php");
    exit();
}

$error = '';
$success = '';
$email_prefill = isset($_SESSION['temp_user']['email']) ? $_SESSION['temp_user']['email'] : '';
$show_forgot_form = isset($_GET['forgot']) ? true : false;
$show_reset_form = false;
$reset_email = '';

// Handle forgot password - Step 1: Ask for email
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_email'])) {
    $email = trim($_POST['email']);
    
    if (empty($email)) {
        $error = "Please enter your email address.";
    } else {
        // Check if email exists in users table
        $stmt = $pdo->prepare("SELECT id, email, first_name FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Email exists, show reset password form
            $show_reset_form = true;
            $reset_email = $email;
            $_SESSION['reset_email'] = $email;
            $_SESSION['reset_user_id'] = $user['id'];
        } else {
            $error = "Email not found. Please register first.";
        }
    }
}

// Handle password reset - Step 2: Update password
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    $email = isset($_SESSION['reset_email']) ? $_SESSION['reset_email'] : '';
    
    if (empty($email)) {
        $error = "Session expired. Please try again.";
        $show_forgot_form = true;
    } elseif (empty($new_password) || empty($confirm_password)) {
        $error = "Please fill in both password fields.";
    } elseif ($new_password !== $confirm_password) {
        $error = "Passwords do not match.";
    } elseif (strlen($new_password) < 6) {
        $error = "Password must be at least 6 characters.";
    } else {
        try {
            // Update password in users table
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("UPDATE users SET password = ? WHERE email = ?");
            $stmt->execute([$hashed_password, $email]);
            
            // Clear session data
            unset($_SESSION['reset_email']);
            unset($_SESSION['reset_user_id']);
            
            $success = "Password has been reset successfully. You can now <a href='" . $_SERVER['PHP_SELF'] . "'>sign in</a>.";
            $show_forgot_form = false;
            $show_reset_form = false;
        } catch (PDOException $e) {
            $error = "An error occurred. Please try again later.";
            error_log("Password reset error: " . $e->getMessage());
        }
    }
}

// Handle sign in
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['signin'])) {
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    if (empty($email) || empty($password)) {
        $error = "Please enter email and password.";
    } else {
        try {
            $stmt = $pdo->prepare("SELECT id, first_name, last_name, email, password FROM users WHERE email = ?");
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['email'] = $user['email'];
                unset($_SESSION['temp_user']);
                header("Location: registration.php");
                exit();
            } else {
                $error = "Invalid email or password.";
            }
        } catch (PDOException $e) {
            $error = "An error occurred. Please try again later.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Sign In | ARC Conference 2026</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
        }
        body::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="rgba(255,255,255,0.1)" fill-opacity="1" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,122.7C672,117,768,139,864,154.7C960,171,1056,181,1152,165.3C1248,149,1344,107,1392,85.3L1440,64L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') no-repeat bottom;
            background-size: cover;
            bottom: 0;
            left: 0;
            pointer-events: none;
        }
        .container {
            max-width: 450px;
            width: 100%;
            background: rgba(255, 255, 255, 0.98);
            border-radius: 32px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            overflow: hidden;
            position: relative;
            z-index: 1;
            animation: slideUp 0.5s ease-out;
        }
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }
        .header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }
        .header p {
            font-size: 14px;
            opacity: 0.9;
        }
        .form-content {
            padding: 40px 30px;
        }
        .input-group {
            margin-bottom: 24px;
            position: relative;
        }
        .input-group i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            font-size: 18px;
        }
        .input-group input {
            width: 100%;
            padding: 14px 16px 14px 48px;
            border: 2px solid #e5e7eb;
            border-radius: 16px;
            font-size: 15px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s;
            background: #f9fafb;
        }
        .input-group input:focus {
            outline: none;
            border-color: #2a5298;
            background: white;
            box-shadow: 0 0 0 4px rgba(42, 82, 152, 0.1);
        }
        .btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            font-family: 'Inter', sans-serif;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(30, 60, 114, 0.4);
        }
        .btn-secondary {
            background: #6b7280;
        }
        .btn-secondary:hover {
            box-shadow: 0 10px 25px -5px rgba(107, 114, 128, 0.4);
        }
        .footer-link {
            text-align: center;
            margin-top: 24px;
            color: #6b7280;
            font-size: 14px;
        }
        .footer-link a {
            color: #2a5298;
            text-decoration: none;
            font-weight: 600;
        }
        .alert {
            padding: 14px 16px;
            border-radius: 16px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .alert-error {
            background: #fee2e2;
            color: #dc2626;
            border-left: 4px solid #dc2626;
        }
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border-left: 4px solid #065f46;
        }
        .alert-success a {
            color: #065f46;
            font-weight: 600;
        }
        .forgot-link {
            text-align: right;
            margin-top: -16px;
            margin-bottom: 24px;
        }
        .forgot-link a {
            color: #6b7280;
            font-size: 13px;
            text-decoration: none;
        }
        .forgot-link a:hover {
            color: #2a5298;
            text-decoration: underline;
        }
        .back-link {
            display: inline-block;
            color: #2a5298;
            text-decoration: none;
            font-weight: 600;
            margin-bottom: 20px;
        }
        .back-link:hover {
            text-decoration: underline;
        }
        .email-display {
            background: #f3f4f6;
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #1e3c72;
            font-weight: 500;
        }
        .email-display i {
            color: #2a5298;
        }
        @media (max-width: 640px) {
            .header {
                padding: 30px 20px;
            }
            .form-content {
                padding: 30px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <?php if ($show_reset_form): ?>
                <h1><i class="fas fa-key"></i> Reset Password</h1>
                <p>Enter your new password</p>
            <?php elseif ($show_forgot_form || isset($_POST['check_email'])): ?>
                <h1><i class="fas fa-envelope"></i> Forgot Password</h1>
                <p>Enter your registered email</p>
            <?php else: ?>
                <h1><i class="fas fa-sign-in-alt"></i> Welcome Back</h1>
                <p>Sign in to continue your registration</p>
            <?php endif; ?>
        </div>
        <div class="form-content">
            <?php if($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo $success; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($show_reset_form): ?>
                <!-- Reset Password Form - Step 2 -->
                <div class="email-display">
                    <i class="fas fa-envelope"></i>
                    Resetting password for: <strong><?php echo htmlspecialchars($reset_email); ?></strong>
                </div>
                <form method="POST" action="">
                    <div class="input-group">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="new_password" placeholder="New Password (min 6 characters)" required minlength="6">
                    </div>
                    <div class="input-group">
                        <i class="fas fa-check-circle"></i>
                        <input type="password" name="confirm_password" placeholder="Confirm New Password" required minlength="6">
                    </div>
                    <button type="submit" name="reset_password" class="btn">
                        <i class="fas fa-save"></i> Update Password
                    </button>
                    <br><br>
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="back-link">
                        <i class="fas fa-arrow-left"></i> Back to Sign In
                    </a>
                </form>
            
            <?php elseif ($show_forgot_form || isset($_POST['check_email'])): ?>
                <!-- Forgot Password Form - Step 1 -->
                <form method="POST" action="?forgot=1">
                    <div class="input-group">
                        <i class="fas fa-envelope"></i>
                        <input type="email" name="email" placeholder="Enter your registered email address" required value="<?php echo htmlspecialchars($email_prefill); ?>">
                    </div>
                    <button type="submit" name="check_email" class="btn">
                        <i class="fas fa-search"></i> Verify Email
                    </button>
                    <br><br>
                    <a href="<?php echo $_SERVER['PHP_SELF']; ?>" class="back-link">
                        <i class="fas fa-arrow-left"></i> Back to Sign In
                    </a>
                </form>
            
            <?php else: ?>
                <!-- Sign In Form -->
                <form method="POST" action="">
                    <div class="input-group">
                        <i class="fas fa-envelope"></i>
                        <input type="email" name="email" placeholder="Email Address" required value="<?php echo htmlspecialchars($email_prefill); ?>">
                    </div>
                    <div class="input-group">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="password" placeholder="Password" required>
                    </div>
                    <div class="forgot-link">
                        <a href="?forgot=1"><i class="fas fa-key"></i> Forgot Password?</a>
                    </div>
                    <button type="submit" name="signin" class="btn">
                        <i class="fas fa-arrow-right"></i> Sign In
                    </button>
                </form>
                <div class="footer-link">
                    Don't have an account? <a href="signup.php">Create Account</a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>