<?php
header('Content-Type: application/json');
session_start();

include_once __DIR__ . '/../../config/dbcon.php';
include_once __DIR__ . '/../../helpers/api_helper.php';

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

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

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

if (!$email || !$password) {
    sendResponse(422, "Email and password required");
}

try {
    $stmt = $conn->prepare("SELECT id, name, phone, password,role FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || !password_verify($password, $user['password'])) {
        sendResponse(401, "Invalid email or password");
    }

    // Store session
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['user_name'] = $user['name'];
    $_SESSION['user_phone'] = $user['phone'];
    $_SESSION['email'] = $email;
    $_SESSION['role'] = $user['role'];



    sendResponse(200, "Login successful", [
        'user_name' => $user['name'],
        'role' => $user['role']
    ]);

} catch (PDOException $e) {
    sendResponse(500, "Database error");
}
