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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

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

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

error_log("Purchase Manager login attempt - Email: $email");

// Validate inputs
if (empty($email) || empty($password)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Email and password are required']);
    exit;
}

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

// Query for purchase manager from purchase_managers table
$stmt = $conn->prepare("SELECT id, name, email, password, phone, status FROM purchase_managers WHERE email = ? AND status = 'active' LIMIT 1");

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$stmt->bind_param('s', $email);

if (!$stmt->execute()) {
    error_log("Execute failed: " . $stmt->error);
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Database error']);
    exit;
}

$result = $stmt->get_result();
$purchase_manager = $result->fetch_assoc();

if (!$purchase_manager) {
    error_log("Purchase Manager user not found: $email");
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Purchase manager account not found or invalid credentials']);
    exit;
}

// Verify password
if (!password_verify($password, $purchase_manager['password'])) {
    error_log("Invalid password for purchase manager: $email");
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'Invalid email or password']);
    exit;
}

// Set session variables
$_SESSION['purchase_manager_id'] = $purchase_manager['id'];
$_SESSION['purchase_manager_email'] = $purchase_manager['email'];
$_SESSION['purchase_manager_name'] = $purchase_manager['name'];
$_SESSION['purchase_manager_phone'] = $purchase_manager['phone'];

$_SESSION['pm_user'] = [
    'id' => $purchase_manager['id'],
    'name' => $purchase_manager['name'],
    'email' => $purchase_manager['email'],
    'phone' => $purchase_manager['phone']
];

// Update last login time
$updateStmt = $conn->prepare("UPDATE purchase_managers SET last_login = NOW() WHERE id = ?");
$updateStmt->bind_param('i', $purchase_manager['id']);
$updateStmt->execute();
$updateStmt->close();

// Generate a token
$token = bin2hex(random_bytes(32));
$_SESSION['pm_token'] = $token;

error_log("Purchase Manager login successful - ID: " . $purchase_manager['id'] . ", Email: " . $purchase_manager['email']);

header('Content-Type: application/json');
echo json_encode([
    'success' => true,
    'message' => 'Login successful',
    'name' => $purchase_manager['name'],
    'email' => $purchase_manager['email']
]);
exit;
?>
