<?php
/**
 * Simple Login API
 * Method: POST
 * Parameters: email, password
 */

// Start session
session_start();

// Include database connection
require_once '../controlls/functions.php';

// Set response headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');

// Function to send JSON response
function sendResponse($success, $message, $data = null) {
    $response = array(
        'success' => (bool)$success,  // Force boolean type
        'message' => $message
    );
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit();
}

// Only accept POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Only POST requests are allowed');
}

// Get input data (support both JSON and form data)
$email = '';
$password = '';

// Try to get JSON input first
$json_input = file_get_contents('php://input');
if (!empty($json_input)) {
    $data = json_decode($json_input, true);
    if ($data) {
        $email = isset($data['email']) ? trim($data['email']) : '';
        $password = isset($data['password']) ? trim($data['password']) : '';
    }
}

// If not JSON, try POST data
if (empty($email) && isset($_POST['email'])) {
    $email = trim($_POST['email']);
}
if (empty($password) && isset($_POST['password'])) {
    $password = trim($_POST['password']);
}

// Validate required fields
if (empty($email)) {
    sendResponse(false, 'Email is required');
}

if (empty($password)) {
    sendResponse(false, 'Password is required');
}

try {
    // Get user from database
    $stmt = $conn->prepare("SELECT * FROM users WHERE email = :email LIMIT 1");
    $stmt->execute(['email' => $email]);
    $user = $stmt->fetch(PDO::FETCH_OBJ);
    
    // Check if user exists
    if (!$user) {
        sendResponse(false, 'Invalid email or password');
    }
    
    // Verify password
    $password_valid = false;
    
    // Try password_verify first (for hashed passwords)
    if (password_verify($password, $user->password)) {
        $password_valid = true;
    } 
    // If that fails, try direct comparison (for plain text passwords)
    else if ($password === $user->password) {
        $password_valid = true;
    }
    
    if (!$password_valid) {
        sendResponse(false, 'Invalid email or password');
    }
    
    // Create session
    $_SESSION['user_login'] = array(
        'id' => $user->id
    );
    
    // Set cookie
    $cookie_name = "bjslcnr";
    $cookie_value = $user->id;
    $cookie_expire = time() + (365 * 24 * 60 * 60); // 1 year
    setcookie($cookie_name, $cookie_value, $cookie_expire, "/");
    
    // Prepare user data for response
    $userData = array(
        'id' => $user->id,
        'email' => $user->email,
        'name' => isset($user->name) ? $user->name : '',
        'phone_number' => isset($user->phone_number) ? $user->phone_number : '',
        'role' => isset($user->role) ? $user->role : ''
    );
    
    // Send success response
    sendResponse(true, 'Login successful', array('user' => $userData));
    
} catch (PDOException $e) {
    // Database error
    sendResponse(false, 'Database connection error');
} catch (Exception $e) {
    // General error
    sendResponse(false, 'An unexpected error occurred');
}