<?php
/**
 * Process Customer Login
 */
require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: login.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';

$error = '';

if (empty($email) || empty($password)) {
    $error = 'Please enter email and password';
} else {
    // Query customers table for customer
    $stmt = $conn->prepare("SELECT id, firstname, lastname, password, role FROM customers WHERE email = ? AND role = 'customer'");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $error = 'Invalid email or this account is not found';
    } else {
        $user = $result->fetch_assoc();
        
        if (!password_verify($password, $user['password'])) {
            $error = 'Invalid password';
        } else {
            // Login successful
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['firstname'] . ' ' . $user['lastname'];
            $_SESSION['user_email'] = $email;
            $_SESSION['user_role'] = $user['role'];

            // Redirect to customer dashboard
            header('Location: dashboards/customer-dashboard.php');
            exit;
        }
    }
    $stmt->close();
}

// If error, redirect back to login with error
header('Location: login.php?error=' . urlencode($error));
exit;
?>
