<?php
require_once 'db.php';
header('Content-Type: application/json');

$pdo = db();
$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

if ($method === 'GET') {
    if ($action === 'list') {
        try {
            $stmt = $pdo->query("
                SELECT i.*, s.supplier_name,
                (SELECT COUNT(*) FROM invoice_items WHERE invoice_id = i.id) as item_count
                FROM invoices i
                LEFT JOIN suppliers s ON i.supplier_id = s.id
                ORDER BY i.id DESC
            ");
            echo json_encode(['ok' => true, 'data' => $stmt->fetchAll()]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
    
    if ($action === 'next_no') {
        $supplier_id = $_GET['supplier_id'] ?? 0;
        // Simple generation logic: INV-{SupplierID}-{Timestamp}
        // You can adjust this logic if you want sequential numbers per supplier or global
        $nextNo = 'INV-' . $supplier_id . '-' . time();
        echo json_encode(['ok' => true, 'invoice_no' => $nextNo]);
        exit;
    }
    
    if ($action === 'get') {
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        if (!$id) {
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'id required']);
            exit;
        }
        try {
            $stmt = $pdo->prepare("
                SELECT i.*, s.supplier_name
                FROM invoices i
                LEFT JOIN suppliers s ON i.supplier_id = s.id
                WHERE i.id = ?
            ");
            $stmt->execute([$id]);
            $inv = $stmt->fetch();
            if (!$inv) {
                http_response_code(404);
                echo json_encode(['ok' => false, 'error' => 'Not found']);
                exit;
            }
            $stmtItems = $pdo->prepare("
                SELECT ii.*, it.item_no, it.code_number
                FROM invoice_items ii
                LEFT JOIN inventory_items it ON ii.item_id = it.id
                WHERE ii.invoice_id = ?
                ORDER BY ii.id ASC
            ");
            $stmtItems->execute([$id]);
            $items = $stmtItems->fetchAll();
            echo json_encode(['ok' => true, 'data' => $inv, 'items' => $items]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
}

if ($method === 'POST') {
    if ($action === 'delete') {
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        if (!$id) {
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'id required']);
            exit;
        }
        try {
            $pdo->beginTransaction();
            $stmtDelItems = $pdo->prepare("DELETE FROM invoice_items WHERE invoice_id = ?");
            $stmtDelItems->execute([$id]);
            $stmtDelInv = $pdo->prepare("DELETE FROM invoices WHERE id = ?");
            $stmtDelInv->execute([$id]);
            $pdo->commit();
            echo json_encode(['ok' => true]);
        } catch (Exception $e) {
            $pdo->rollBack();
            http_response_code(500);
            echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
        }
        exit;
    }
    // Check if it's a multipart form data request (file upload)
    if (!empty($_POST) || !empty($_FILES)) {
        $data = $_POST;
        if (isset($data['items']) && is_string($data['items'])) {
            $data['items'] = json_decode($data['items'], true);
        }
    } else {
        // Fallback to JSON input
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
    }
    
    if (!$data) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid data']);
        exit;
    }

    try {
        $pdo->beginTransaction();

        // Handle File Upload
        $imagePath = null;
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = '../uploads/invoices/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileName = time() . '_' . basename($_FILES['image']['name']);
            $targetPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($_FILES['image']['tmp_name'], $targetPath)) {
                $imagePath = 'uploads/invoices/' . $fileName;
            }
        }
        
        $invoice_no = isset($data['invoice_no']) ? (string)$data['invoice_no'] : '';
        $supplier_id = isset($data['supplier_id']) ? (int)$data['supplier_id'] : 0;
        $batch_no = isset($data['batch_no']) ? (string)$data['batch_no'] : '';
        $maturity_date = isset($data['maturity_date']) && $data['maturity_date'] !== '' ? (string)$data['maturity_date'] : null;
        $currency = isset($data['currency']) ? (string)$data['currency'] : '';
        $exchange_rate = isset($data['exchange_rate']) ? (float)$data['exchange_rate'] : 1.0;
        $current_expense = isset($data['current_expense']) ? (float)$data['current_expense'] : 0.0;
        $discount = isset($data['discount']) ? (float)$data['discount'] : 0.0;
        $id = isset($data['id']) ? (int)$data['id'] : 0;

        if (!$action || $action === 'create') {
            $stmt = $pdo->prepare("
                INSERT INTO invoices 
                (invoice_no, supplier_id, batch_no, maturity_date, currency, exchange_rate, current_expense, discount, image_path)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $invoice_no,
                $supplier_id,
                $batch_no,
                $maturity_date,
                $currency,
                $exchange_rate,
                $current_expense,
                $discount,
                $imagePath
            ]);
            
            $invoice_id = $pdo->lastInsertId();
        } else if ($action === 'update') {
            if (!$id) {
                http_response_code(400);
                echo json_encode(['ok' => false, 'error' => 'id required']);
                exit;
            }
            // Keep old image if not uploading a new one
            if ($imagePath === null) {
                $stmtImg = $pdo->prepare("SELECT image_path FROM invoices WHERE id = ?");
                $stmtImg->execute([$id]);
                $imagePath = $stmtImg->fetchColumn();
            }
            $stmt = $pdo->prepare("
                UPDATE invoices
                SET invoice_no = ?, supplier_id = ?, batch_no = ?, maturity_date = ?, currency = ?, exchange_rate = ?, current_expense = ?, discount = ?, image_path = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $invoice_no,
                $supplier_id,
                $batch_no,
                $maturity_date,
                $currency,
                $exchange_rate,
                $current_expense,
                $discount,
                $imagePath,
                $id
            ]);
            $invoice_id = $id;
            // Replace items
            $stmtDel = $pdo->prepare("DELETE FROM invoice_items WHERE invoice_id = ?");
            $stmtDel->execute([$invoice_id]);
        } else {
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'invalid action']);
            exit;
        }
        
        if (!empty($data['items']) && is_array($data['items'])) {
            $stmtItem = $pdo->prepare("
                INSERT INTO invoice_items
                (invoice_id, item_id, quantity, unit_price, weight, total_amount)
                VALUES (?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($data['items'] as $item) {
                $item_id = isset($item['item_id']) ? (int)$item['item_id'] : 0;
                $quantity = isset($item['quantity']) ? (float)$item['quantity'] : 0.0;
                $unit_price = isset($item['unit_price']) ? (float)$item['unit_price'] : 0.0;
                $weight = isset($item['weight']) ? (float)$item['weight'] : 0.0;
                $total_amount = isset($item['total_amount']) ? (float)$item['total_amount'] : ($quantity * $unit_price);

                $stmtItem->execute([
                    $invoice_id,
                    $item_id,
                    $quantity,
                    $unit_price,
                    $weight,
                    $total_amount
                ]);
            }
        }
        
        $pdo->commit();
        echo json_encode(['ok' => true, 'id' => (int)$invoice_id]);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
