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

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

    // Restaurant details
    $restaurant_name = $_POST['restaurant_name'];
    $restaurant_address = $_POST['restaurant_address'];
    $restaurant_phone = $_POST['restaurant_phone'];

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

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

    try {
        $pdo = db();

        // Check if email already exists
        $sql = "SELECT id FROM users WHERE email = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            die('Email already exists.');
        }

        // Create the user with 'restaurant_owner' role
        $password_hash = password_hash($password, PASSWORD_BCRYPT);
        $sql = "INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, 'restaurant_owner')";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$name, $email, $password_hash]);
        $user_id = $pdo->lastInsertId();

        // Create the restaurant
        $sql = "INSERT INTO restaurants (name, address, phone_number, user_id) VALUES (?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$restaurant_name, $restaurant_address, $restaurant_phone, $user_id]);
        $restaurant_id = $pdo->lastInsertId();

        // Log the user in
        $_SESSION['user_id'] = $user_id;
        $_SESSION['user_name'] = $name;
        $_SESSION['user_role'] = 'restaurant_owner';
        $_SESSION['restaurant_id'] = $restaurant_id;

        // Redirect to the restaurant dashboard
        header("Location: restaurant/index.php");
        exit;

    } catch (PDOException $e) {
        die("Could not connect to the database: " . $e->getMessage());
    }
}
?>