<?php
session_start();
require_once 'db/config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (empty($email) || empty($password)) {
        die('Please fill all required fields.');
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        die('Invalid email format.');
    }

    try {
        $pdo = db();

        $sql = "SELECT * FROM users WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && password_verify($password, $user['password'])) {
            if ($user['role'] !== 'restaurant_owner') {
                die('You are not authorized to access this page.');
            }

            // Fetch the restaurant ID
            $sql = "SELECT id FROM restaurants WHERE user_id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$user['id']]);
            $restaurant = $stmt->fetch(PDO::FETCH_ASSOC);

            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['name'];
            $_SESSION['user_role'] = $user['role'];
            if ($restaurant) {
                $_SESSION['restaurant_id'] = $restaurant['id'];
            }

            header("Location: restaurant/index.php");
            exit;
        } else {
            die('Invalid email or password.');
        }
    } catch (PDOException $e) {
        die("Could not connect to the database: " . $e->getMessage());
    }
}
?>