<?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();

        if ($user && password_verify($password, $user['password'])) {
            $user_id = $user['id'];
            $session_id = session_id();

            // Merge guest cart with user cart
            $merge_sql = "UPDATE cart SET user_id = ?, session_id = NULL WHERE session_id = ?";
            $merge_stmt = $pdo->prepare($merge_sql);
            $merge_stmt->execute([$user_id, $session_id]);

            $_SESSION['user_id'] = $user_id;
            $_SESSION['user_name'] = $user['name'];
            header("Location: index.php");
            exit;
        } else {
            die('Invalid email or password.');
        }
    } catch (PDOException $e) {
        die("Could not connect to the database $dbname :" . $e->getMessage());
    }
}
?>