<?php
/**
 * Suppliers API
 */

session_start();
include 'config.php';

if (!isset($_SESSION['purchase_manager_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$pm_id = (int)$_SESSION['purchase_manager_id'];
$action = isset($_GET['action']) ? $_GET['action'] : '';
$rawInput = file_get_contents('php://input');
$payload = json_decode($rawInput, true);
if (!$action && is_array($payload)) {
    $action = $payload['action'] ?? '';
}

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

if ($action === 'get_all') {
    $stmt = $conn->prepare("
        SELECT id, name, contact_person, email, phone, address, rating, lead_time_days, payment_terms, status, created_at
        FROM suppliers
        WHERE purchase_manager_id = ?
        ORDER BY name ASC
    ");
    $stmt->bind_param('i', $pm_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $suppliers = [];
    while ($row = $result->fetch_assoc()) {
        $suppliers[] = $row;
    }

    echo json_encode(['success' => true, 'suppliers' => $suppliers]);
    exit;
}

if ($action === 'get_one') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $stmt = $conn->prepare("
        SELECT id, name, contact_person, email, phone, address, rating, lead_time_days, payment_terms, status, created_at
        FROM suppliers
        WHERE id = ? AND purchase_manager_id = ?
    ");
    $stmt->bind_param('ii', $id, $pm_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $supplier = $result->fetch_assoc();

    if (!$supplier) {
        echo json_encode(['success' => false, 'message' => 'Supplier not found']);
        exit;
    }

    echo json_encode(['success' => true, 'supplier' => $supplier]);
    exit;
}

if ($action === 'create' || $action === 'update') {
    $data = is_array($payload) ? $payload : [];

    $name = trim($data['name'] ?? '');
    $contact_person = trim($data['contact_person'] ?? '');
    $email = trim($data['email'] ?? '');
    $phone = trim($data['phone'] ?? '');
    $address = trim($data['address'] ?? '');
    $rating = isset($data['rating']) && $data['rating'] !== '' ? (float)$data['rating'] : null;
    $lead_time_days = isset($data['lead_time_days']) ? (int)$data['lead_time_days'] : 0;
    $payment_terms = trim($data['payment_terms'] ?? '');
    $status = in_array(($data['status'] ?? 'active'), ['active', 'inactive'], true) ? $data['status'] : 'active';

    if ($name === '' || $contact_person === '' || $email === '' || $phone === '') {
        echo json_encode(['success' => false, 'message' => 'Name, contact person, email, and phone are required']);
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Invalid supplier email']);
        exit;
    }

    if ($action === 'create') {
        $stmt = $conn->prepare("
            INSERT INTO suppliers (
                purchase_manager_id, name, contact_person, email, phone, address, rating, lead_time_days, payment_terms, status, created_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        $stmt->bind_param('isssssdiss', $pm_id, $name, $contact_person, $email, $phone, $address, $rating, $lead_time_days, $payment_terms, $status);
        $ok = $stmt->execute();
        echo json_encode([
            'success' => $ok,
            'message' => $ok ? 'Supplier created successfully' : 'Failed to create supplier'
        ]);
        exit;
    }

    $id = isset($data['id']) ? (int)$data['id'] : 0;
    $stmt = $conn->prepare("
        UPDATE suppliers
        SET name = ?, contact_person = ?, email = ?, phone = ?, address = ?, rating = ?, lead_time_days = ?, payment_terms = ?, status = ?
        WHERE id = ? AND purchase_manager_id = ?
    ");
    $stmt->bind_param('sssssdissii', $name, $contact_person, $email, $phone, $address, $rating, $lead_time_days, $payment_terms, $status, $id, $pm_id);
    $ok = $stmt->execute();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Supplier updated successfully' : 'Failed to update supplier'
    ]);
    exit;
}

if ($action === 'delete') {
    $data = is_array($payload) ? $payload : [];
    $id = isset($data['id']) ? (int)$data['id'] : 0;

    $stmt = $conn->prepare("DELETE FROM suppliers WHERE id = ? AND purchase_manager_id = ?");
    $stmt->bind_param('ii', $id, $pm_id);
    $ok = $stmt->execute();

    echo json_encode([
        'success' => $ok,
        'message' => $ok ? 'Supplier deleted successfully' : 'Failed to delete supplier'
    ]);
    exit;
}

echo json_encode(['success' => false, 'message' => 'Invalid action']);
