<?php
session_start();
require_once 'db.php';

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

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

$action = $_GET['action'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'list') {
        $sql = "SELECT p.*, s.name as supplier_name, u.username as creator
                FROM purchases p
                LEFT JOIN suppliers s ON p.supplier_id = s.id
                JOIN users u ON p.user_id = u.id
                ORDER BY p.purchase_date DESC";
        $stmt = $pdo->query($sql);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
    } elseif ($action === 'details') {
        $id = $_GET['id'] ?? null;
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'ID required']);
            exit;
        }

        $stmt = $pdo->prepare("SELECT p.*, s.name as supplier_name, s.contact_person, s.phone, s.email, s.address, s.tin, u.username as creator
                                FROM purchases p
                                LEFT JOIN suppliers s ON p.supplier_id = s.id
                                JOIN users u ON p.user_id = u.id
                                WHERE p.id = ?");
        $stmt->execute([$id]);
        $purchase = $stmt->fetch();

        if ($purchase) {
            $itemStmt = $pdo->prepare("SELECT pi.*, pr.name as product_name, pr.sku
                                        FROM purchase_items pi
                                        JOIN products pr ON pi.product_id = pr.id
                                        WHERE pi.purchase_id = ?");
            $itemStmt->execute([$id]);
            $purchase['items'] = $itemStmt->fetchAll();
            echo json_encode(['success' => true, 'data' => $purchase]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Purchase not found']);
        }
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        $data = json_decode(file_get_contents("php://input"), true);
        if (!$data || empty($data['items'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid data or empty items']);
            exit;
        }

        $supplier_id = $data['supplier_id'] ?? null;
        $total_amount = $data['total_amount'] ?? 0;
        
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO purchases (supplier_id, total_amount, user_id, status) VALUES (?, ?, ?, 'Pending')");
            $stmt->execute([$supplier_id, $total_amount, $_SESSION['user_id']]);
            $purchase_id = $pdo->lastInsertId();

            $itemStmt = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, subtotal) VALUES (?, ?, ?, ?, ?)");
            foreach ($data['items'] as $item) {
                $subtotal = ($item['quantity'] ?? 0) * ($item['cost_price'] ?? 0);
                $itemStmt->execute([$purchase_id, $item['product_id'], $item['quantity'], $item['cost_price'], $subtotal]);
            }
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Purchase order created successfully.', 'id' => $purchase_id]);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    } elseif ($action === 'update') {
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['id'] ?? null;
        if (!$id || empty($data['items'])) {
            echo json_encode(['success' => false, 'message' => 'ID and items required']);
            exit;
        }

        try {
            $pdo->beginTransaction();
            // Check status - only Pending can be updated
            $stmt = $pdo->prepare("SELECT status FROM purchases WHERE id = ?");
            $stmt->execute([$id]);
            $p = $stmt->fetch();
            if (!$p || ($p['status'] !== 'Pending' && $p['status'] !== 'Partial')) {
                throw new Exception("Only Pending or Partial purchase orders can be updated.");
            }

            // Update main record
            $supplier_id = $data['supplier_id'] ?? null;
            $total_amount = $data['total_amount'] ?? 0;
            $pdo->prepare("UPDATE purchases SET supplier_id = ?, total_amount = ? WHERE id = ?")->execute([$supplier_id, $total_amount, $id]);

            // Re-sync items: Delete old, Insert new (simplest for CRUD management)
            $pdo->prepare("DELETE FROM purchase_items WHERE purchase_id = ?")->execute([$id]);
            $itemStmt = $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, quantity, cost_price, subtotal) VALUES (?, ?, ?, ?, ?)");
            foreach ($data['items'] as $item) {
                $subtotal = ($item['quantity'] ?? 0) * ($item['cost_price'] ?? 0);
                $itemStmt->execute([$id, $item['product_id'], $item['quantity'], $item['cost_price'], $subtotal]);
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Purchase order updated successfully.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'] ?? null;
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'ID required']);
            exit;
        }

        try {
            $pdo->beginTransaction();
            // Check if it has receptions
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM receptions WHERE purchase_id = ?");
            $stmt->execute([$id]);
            if ($stmt->fetchColumn() > 0) {
                throw new Exception("Cannot delete a purchase order that has already received goods. Please cancel/reverse it instead.");
            }

            $pdo->prepare("DELETE FROM purchase_items WHERE purchase_id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM purchases WHERE id = ?")->execute([$id]);

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Purchase order deleted successfully.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
    } elseif ($action === 'uncancel') {
        $id = $_POST['id'] ?? null;
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'ID required']);
            exit;
        }

        try {
            $pdo->beginTransaction();

            // 1. Get PO info
            $stmt = $pdo->prepare("SELECT status FROM purchases WHERE id = ?");
            $stmt->execute([$id]);
            $p = $stmt->fetch();
            if (!$p || $p['status'] !== 'Cancelled') {
                throw new Exception("Only Cancelled purchase orders can be uncancelled.");
            }

            // 2. Re-add the stock that was reversed on cancellation
            $recStmt = $pdo->prepare("SELECT product_id, SUM(quantity_received) as total_received 
                                      FROM reception_items 
                                      WHERE reception_id IN (SELECT id FROM receptions WHERE purchase_id = ?)
                                      GROUP BY product_id");
            $recStmt->execute([$id]);
            $receptions = $recStmt->fetchAll();

            $updateStock = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity + ? WHERE id = ?");
            foreach ($receptions as $rec) {
                if ($rec['total_received'] > 0) {
                    $updateStock->execute([$rec['total_received'], $rec['product_id']]);
                }
            }

            // 3. Determine new status: if it has receptions, it might be Received/Partial. If not, it's Pending.
            $hasRecStmt = $pdo->prepare("SELECT COUNT(*) FROM receptions WHERE purchase_id = ?");
            $hasRecStmt->execute([$id]);
            $numRec = $hasRecStmt->fetchColumn();
            
            $newStatus = ($numRec > 0) ? 'Partial' : 'Pending';

            $pdo->prepare("UPDATE purchases SET status = ? WHERE id = ?")->execute([$newStatus, $id]);

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Purchase order restored. Stock re-added for previous deliveries.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
    } elseif ($action === 'reverse') {
        $id = $_POST['id'] ?? null;
        if (!$id) {
            echo json_encode(['success' => false, 'message' => 'ID required']);
            exit;
        }

        try {
            $pdo->beginTransaction();

            // 1. Check if already cancelled
            $stmt = $pdo->prepare("SELECT status FROM purchases WHERE id = ?");
            $stmt->execute([$id]);
            $p = $stmt->fetch();
            if (!$p || $p['status'] === 'Cancelled') {
                throw new Exception("Purchase record not found or already reversed.");
            }

            // 2. Get TOTAL received quantities for this PO and reverse stock
            $recStmt = $pdo->prepare("SELECT product_id, SUM(quantity_received) as total_received 
                                      FROM reception_items 
                                      WHERE reception_id IN (SELECT id FROM receptions WHERE purchase_id = ?)
                                      GROUP BY product_id");
            $recStmt->execute([$id]);
            $receptions = $recStmt->fetchAll();

            $updateStock = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?");
            foreach ($receptions as $rec) {
                if ($rec['total_received'] > 0) {
                    $updateStock->execute([$rec['total_received'], $rec['product_id']]);
                }
            }

            // 3. Update status to Cancelled
            $pdo->prepare("UPDATE purchases SET status = 'Cancelled' WHERE id = ?")->execute([$id]);

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Purchase order cancelled. Stock adjusted based on received quantities.']);
        } catch (Exception $e) {
            $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
    }
}
