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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? ''; // This can be email or phone
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => 'Username/Email and Password are required.']);
        exit;
    }

    try {
        // Search by email OR phone
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? OR phone_number = ?");
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            // Check if user is active
            if (isset($user['is_active']) && $user['is_active'] == 0) {
                echo json_encode(['status' => 'error', 'message' => 'Your account has been deactivated. Please contact support.']);
                exit;
            }

            // Success! Store in session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['full_name'] = $user['full_name'];
            $_SESSION['role'] = $user['role'] ?? 'customer';
            
            // If admin, also set the admin specific session variables
            if ($_SESSION['role'] === 'admin') {
                $_SESSION['admin_id'] = $user['id'];
                $_SESSION['admin_name'] = $user['full_name'];
                $_SESSION['admin_email'] = $user['email'];
                $_SESSION['admin_logged_in'] = true;
            }
            
            echo json_encode([
                'status' => 'success', 
                'message' => 'Login successful!',
                'user' => [
                    'id' => $user['id'],
                    'full_name' => $user['full_name'],
                    'email' => $user['email'],
                    'role' => $_SESSION['role']
                ]
            ]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid credential']);
        }
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
}
?>
