<?php
require_once 'db.php';

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

$method = $_SERVER['REQUEST_METHOD'];
$pdo = db();

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';

    if ($action === 'next_id') {
        // Get the last Demand ID
        $stmt = $pdo->query("SELECT demand_id FROM purchase_demands ORDER BY id DESC LIMIT 1");
        $last = $stmt->fetchColumn();

        if ($last) {
            // Extract number part. Assuming format PD-XX
            if (preg_match('/PD-(\d+)/', $last, $matches)) {
                $num = intval($matches[1]);
                $nextNum = $num + 1;
                $nextId = 'PD-' . str_pad($nextNum, 2, '0', STR_PAD_LEFT);
            } else {
                $nextId = 'PD-01';
            }
        } else {
            $nextId = 'PD-01';
        }
        echo json_encode(['next_id' => $nextId]);
        exit;
    }

    if ($action === 'list') {
        // Join with suppliers and inventory_items
        $stmt = $pdo->query("
            SELECT p.*, s.supplier_name, i.item_no, i.code_number
            FROM purchase_demands p
            LEFT JOIN suppliers s ON p.supplier_id = s.id
            LEFT JOIN inventory_items i ON p.item_id = i.id
            ORDER BY p.id DESC
        ");
        echo json_encode($stmt->fetchAll());
        exit;
    }
    if ($action === 'get') {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        $stmt = $pdo->prepare("
            SELECT p.*, s.supplier_name, i.item_no, i.code_number
            FROM purchase_demands p
            LEFT JOIN suppliers s ON p.supplier_id = s.id
            LEFT JOIN inventory_items i ON p.item_id = i.id
            WHERE p.id = ?
        ");
        $stmt->execute([$id]);
        $row = $stmt->fetch();
        if (!$row) {
            http_response_code(404);
            echo json_encode(['error' => 'Not found']);
            exit;
        }
        echo json_encode($row);
        exit;
    }
} elseif ($method === 'POST') {
    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'create';
    $data = json_decode(file_get_contents('php://input'), true);
    if (!$data) $data = $_POST;

    $demand_id = $data['demand_id'] ?? '';
    $supplier_id = $data['supplier_id'] ?? '';
    $item_id = $data['item_id'] ?? '';
    $priority = $data['priority'] ?? '';
    $notes = $data['notes'] ?? '';

    try {
        if ($action === 'create') {
            if (empty($demand_id) || empty($supplier_id) || empty($item_id) || empty($priority)) {
                http_response_code(400);
                echo json_encode(['error' => 'Missing required fields']);
                exit;
            }
            $stmt = $pdo->prepare("
                INSERT INTO purchase_demands 
                (demand_id, supplier_id, item_id, priority, notes)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([$demand_id, $supplier_id, $item_id, $priority, $notes]);
            echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
            exit;
        }
        if ($action === 'update') {
            $id = isset($data['id']) ? (int)$data['id'] : 0;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['error' => 'ID required']);
                exit;
            }
            if (empty($demand_id) || empty($supplier_id) || empty($item_id) || empty($priority)) {
                http_response_code(400);
                echo json_encode(['error' => 'Missing required fields']);
                exit;
            }
            $stmt = $pdo->prepare("
                UPDATE purchase_demands
                SET demand_id=?, supplier_id=?, item_id=?, priority=?, notes=?
                WHERE id=?
            ");
            $stmt->execute([$demand_id, $supplier_id, $item_id, $priority, $notes, $id]);
            echo json_encode(['success' => true]);
            exit;
        }
        if ($action === 'delete') {
            $id = isset($data['id']) ? (int)$data['id'] : 0;
            if (!$id) {
                http_response_code(400);
                echo json_encode(['error' => 'ID required']);
                exit;
            }
            $stmt = $pdo->prepare("DELETE FROM purchase_demands WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['success' => true]);
            exit;
        }
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
        exit;
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
}
