<?php
require 'require/conn.php';
session_start();

// Prevent session fixation attacks
session_regenerate_id(true);

// Function to sanitize input
function sanitizeInput($data) {
    return htmlspecialchars(stripslashes(trim($data)));
}

// Initialize error variable
$error = "";

// Handle login request
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $phone = sanitizeInput($_POST['phone']);
    $password = sanitizeInput($_POST['password']);

    if (empty($phone) || empty($password)) {
        $error = "All fields are required.";
    } else {
        // Check if the user exists (search by phone)
        $query = "SELECT id, firstName, lastName, phone, password FROM jamaa WHERE phone = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $phone);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows == 1) {
            $user = $result->fetch_assoc();

            // Hash input password using SHA-256 (first 10 characters)
            $hashedInputPassword = substr(hash('sha256', $password), 0, 10);

            if ($hashedInputPassword === $user['password']) {
                // Store session data
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['firstName'] = $user['firstName'];
                $_SESSION['lastName'] = $user['lastName'];
                $_SESSION['phone'] = $user['phone'];

                // Set a cookie with the phone number (Remember Me feature)
                setcookie("phone", $user['phone'], time() + (86400 * 30), "/"); // Expires in 30 days

                // Redirect to dashboard
                header("Location: dashboard.php");
                exit();
            } else {
                $error = "Invalid password.";
            }
        } else {
            $error = "No account found, kindly register.";
        }

        $stmt->close();
    }
}

// Handle switch user action
if (isset($_GET['action']) && $_GET['action'] === 'switch_user') {
    setcookie("phone", "", time() - 3600, "/"); // Expire the cookie
    header("Location: login.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f4f4f4;
        }
        .login-container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            max-width: 400px;
            width: 100%;
        }
        .login-container h1 {
            margin-bottom: 10px;
            font-size: 24px;
        }
        .login-container p {
            margin-bottom: 20px;
            color: #666;
        }
        .login-container label {
            display: block;
            margin-bottom: 5px;
            text-align: left;
        }
        .login-container input {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .login-container button {
            width: 100%;
            padding: 10px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .login-container button:hover {
            background-color: #218838;
        }
        .login-container a {
            display: block;
            margin-top: 10px;
            color: #007bff;
            text-decoration: none;
        }
        .login-container a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h1>Welcome Back!</h1>
        <p>Kindly Login with Phone No. and Password</p>

        <form method="POST" action="">
            <?php if (isset($_COOKIE['phone'])): ?>
                <p>Welcome back, <?= htmlspecialchars($_COOKIE['phone']); ?></p>
                <input type="hidden" name="phone" value="<?= htmlspecialchars($_COOKIE['phone']); ?>">
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            <?php else: ?>
                <label for="phone">Phone Number:</label>
                <input type="text" id="phone" name="phone" value="<?= isset($_COOKIE['phone']) ? htmlspecialchars($_COOKIE['phone']) : ''; ?>" required>
                <label for="password">Password:</label>
                <input type="password" id="password" name="password" required>
            <?php endif; ?>
            <button type="submit">Login</button>
        </form>

        <a href="forgot.php">Forgot Password</a>

        <?php if (isset($_COOKIE['phone'])): ?>
            <a href="login.php?action=switch_user">Switch User</a>
        <?php endif; ?>
    </div>

    <!-- Display SweetAlert for errors -->
    <?php if (!empty($error)): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Login Failed!',
            text: '<?= $error; ?>',
            confirmButtonColor: '#d33',
            confirmButtonText: 'Try Again'
        });
    </script>
    <?php endif; ?>
</body>
</html>
