<?php
require_once '../config.php';

try {
    $user = validateToken($conn);
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        // Get all invoices with optional filters
        $customer_id = intval($_GET['customer_id'] ?? 0);
        $customer_type = sanitizeInput($_GET['customer_type'] ?? '');
        $status = sanitizeInput($_GET['status'] ?? '');
        $page = intval($_GET['page'] ?? 1);
        $limit = intval($_GET['limit'] ?? 20);
        $offset = ($page - 1) * $limit;
        
        $whereConditions = [];
        $params = [];
        $types = '';
        
        if (!empty($customer_id)) {
            $whereConditions[] = "customer_id = ?";
            $params[] = $customer_id;
            $types .= 'i';
        }
        
        if (!empty($customer_type)) {
            $whereConditions[] = "customer_type = ?";
            $params[] = $customer_type;
            $types .= 's';
        }
        
        if (!empty($status)) {
            $whereConditions[] = "status = ?";
            $params[] = $status;
            $types .= 's';
        }
        
        $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
        
        // Get total count
        $countSql = "SELECT COUNT(*) as total FROM invoices $whereClause";
        $countStmt = $conn->prepare($countSql);
        if (!empty($params)) {
            $countStmt->bind_param($types, ...$params);
        }
        $countStmt->execute();
        $totalCount = $countStmt->get_result()->fetch_assoc()['total'];
        
        // Get invoices
        $sql = "SELECT * FROM invoices $whereClause ORDER BY created_at DESC LIMIT ? OFFSET ?";
        $stmt = $conn->prepare($sql);
        
        if (!empty($params)) {
            $stmt->bind_param($types . 'ii', ...$params, $limit, $offset);
        } else {
            $stmt->bind_param('ii', $limit, $offset);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $invoices = [];
        while ($row = $result->fetch_assoc()) {
            // Get invoice items
            $itemsStmt = $conn->prepare("
                SELECT ii.*, p.name as product_name, p.sell_price 
                FROM invoice_items ii 
                LEFT JOIN products p ON ii.product_id = p.id 
                WHERE ii.invoice_id = ?
            ");
            $itemsStmt->bind_param("i", $row['id']);
            $itemsStmt->execute();
            $itemsResult = $itemsStmt->get_result();
            
            $items = [];
            while ($item = $itemsResult->fetch_assoc()) {
                $items[] = $item;
            }
            
            $row['items'] = $items;
            $invoices[] = $row;
        }
        
        sendResponse(true, 'Invoices retrieved successfully', [
            'invoices' => $invoices,
            'pagination' => [
                'current_page' => $page,
                'per_page' => $limit,
                'total' => $totalCount,
                'total_pages' => ceil($totalCount / $limit)
            ]
        ]);
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Create new invoice
        $input = json_decode(file_get_contents('php://input'), true);
        
        $customer_id = intval($input['customer_id'] ?? 0);
        $customer_type = sanitizeInput($input['customer_type'] ?? 'permanent');
        $items = $input['items'] ?? [];
        $notes = sanitizeInput($input['notes'] ?? '');
        
        if (empty($customer_id) || empty($items)) {
            sendResponse(false, 'Customer ID and items are required', null, 400);
        }
        
        if (!in_array($customer_type, ['permanent', 'temporary'])) {
            sendResponse(false, 'Invalid customer type', null, 400);
        }
        
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // Calculate totals
            $subtotal = 0;
            $tax_amount = 0;
            $total_amount = 0;
            
            foreach ($items as $item) {
                $product_id = intval($item['product_id']);
                $quantity = intval($item['quantity']);
                $price = floatval($item['price']);
                
                $item_total = $quantity * $price;
                $subtotal += $item_total;
            }
            
            $tax_amount = $subtotal * 0.18; // 18% GST
            $total_amount = $subtotal + $tax_amount;
            
            // Insert invoice
            $invoiceStmt = $conn->prepare("
                INSERT INTO invoices (customer_id, customer_type, subtotal, tax_amount, total_amount, status, notes, created_at) 
                VALUES (?, ?, ?, ?, ?, 'pending', ?, NOW())
            ");
            $invoiceStmt->bind_param("isddds", $customer_id, $customer_type, $subtotal, $tax_amount, $total_amount, $notes);
            $invoiceStmt->execute();
            
            $invoice_id = $conn->insert_id;
            
            // Insert invoice items
            foreach ($items as $item) {
                $product_id = intval($item['product_id']);
                $quantity = intval($item['quantity']);
                $price = floatval($item['price']);
                
                $itemStmt = $conn->prepare("
                    INSERT INTO invoice_items (invoice_id, product_id, quantity, price) 
                    VALUES (?, ?, ?, ?)
                ");
                $itemStmt->bind_param("iiid", $invoice_id, $product_id, $quantity, $price);
                $itemStmt->execute();
                
                // Update product quantity
                $updateStmt = $conn->prepare("UPDATE products SET quantity = quantity - ? WHERE id = ?");
                $updateStmt->bind_param("ii", $quantity, $product_id);
                $updateStmt->execute();
            }
            
            $conn->commit();
            
            sendResponse(true, 'Invoice created successfully', [
                'invoice_id' => $invoice_id,
                'customer_id' => $customer_id,
                'customer_type' => $customer_type,
                'subtotal' => $subtotal,
                'tax_amount' => $tax_amount,
                'total_amount' => $total_amount,
                'status' => 'pending',
                'notes' => $notes
            ]);
            
        } catch (Exception $e) {
            $conn->rollback();
            throw $e;
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
        // Update invoice status
        $input = json_decode(file_get_contents('php://input'), true);
        
        $invoice_id = intval($input['invoice_id'] ?? 0);
        $status = sanitizeInput($input['status'] ?? '');
        
        if (empty($invoice_id) || empty($status)) {
            sendResponse(false, 'Invoice ID and status are required', null, 400);
        }
        
        if (!in_array($status, ['pending', 'completed', 'cancelled'])) {
            sendResponse(false, 'Invalid status', null, 400);
        }
        
        $stmt = $conn->prepare("UPDATE invoices SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $status, $invoice_id);
        
        if ($stmt->execute()) {
            if ($stmt->affected_rows > 0) {
                sendResponse(true, 'Invoice status updated successfully', [
                    'invoice_id' => $invoice_id,
                    'status' => $status
                ]);
            } else {
                sendResponse(false, 'Invoice not found', null, 404);
            }
        } else {
            sendResponse(false, 'Failed to update invoice status', null, 500);
        }
        
    } else {
        sendResponse(false, 'Method not allowed', null, 405);
    }
    
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollback();
    }
    sendResponse(false, 'Operation failed: ' . $e->getMessage(), null, 500);
}
?>
