<?php
session_start();
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Invalid request method');
}

$data = json_decode(file_get_contents("php://input"), true);

// Validate input
if (!isset($data['email']) || !isset($data['password'])) {
    sendResponse(false, 'Email and password are required');
}

$email = trim($data['email']);
$password = $data['password'];

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    sendResponse(false, 'Invalid email format');
}

// Get user from database
$stmt = $conn->prepare("SELECT id, name, email, password, phone, is_email_verified FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    sendResponse(false, 'Invalid email or password');
}

$user = $result->fetch_assoc();

// Check if email is verified
if (!$user['is_email_verified']) {
    sendResponse(false, 'Email not verified. Please verify your email before signing in.');
}

// Verify password
if (!verifyPassword($password, $user['password'])) {
    sendResponse(false, 'Invalid email or password');
}

// Set session
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_email'] = $user['email'];

// Set cookie for "Remember Me"
if (isset($data['rememberMe']) && $data['rememberMe']) {
    setcookie('user_id', $user['id'], time() + (86400 * 30), "/"); // 30 days
    setcookie('user_email', $user['email'], time() + (86400 * 30), "/");
}

sendResponse(true, 'Sign in successful', [
    'id' => $user['id'],
    'name' => $user['name'],
    'email' => $user['email'],
    'phone' => $user['phone']
]);

$stmt->close();
$conn->close();
?>
