<?php
session_start();
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/ServiceModule.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$auth->requireLogin();

function redirectServices($message, $isError = false, $branchId = null, $type = null) {
    $key = $isError ? 'error' : 'success';
    $url = 'index.php?' . $key . '=' . urlencode($message);
    if ($branchId) {
        $url .= '&branch_id=' . (int)$branchId;
    }
    if ($type) {
        $url .= '&type=' . urlencode($type);
    }
    header('Location: ' . $url);
    exit();
}

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        redirectServices('Invalid request.', true);
    }

    $action = $_POST['action'] ?? '';
    if ($action !== 'create_invoice') {
        redirectServices('Unknown services action.', true);
    }

    $role = strtolower((string)($_SESSION['role'] ?? ''));
    $canSeeAll = in_array($role, ['admin', 'super_admin', 'controller'], true) || $auth->isSuperAdmin($_SESSION['user_id']);
    $userBranchId = (int)$auth->getUserBranch($_SESSION['user_id']);
    $branchId = (int)($_POST['branch_id'] ?? 0);
    if (!$canSeeAll) {
        $branchId = $userBranchId;
    }
    if ($branchId <= 0) {
        redirectServices('A valid branch is required.', true);
    }
    if (!$canSeeAll && $branchId !== $userBranchId) {
        redirectServices('You can only record services for your assigned branch.', true);
    }

    $lineTypes = $_POST['line_type'] ?? [];
    $siteProductIds = $_POST['site_product_id'] ?? [];
    $serviceNames = $_POST['service_name'] ?? [];
    $productCodes = $_POST['product_code'] ?? [];
    $descriptions = $_POST['description'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $unitPrices = $_POST['unit_price'] ?? [];
    $discounts = $_POST['discount_amount'] ?? [];
    $lines = [];
    $count = max(count($siteProductIds), count($serviceNames), count($productCodes), count($unitPrices), count($lineTypes));
    for ($i = 0; $i < $count; $i++) {
        $serviceName = trim((string)($serviceNames[$i] ?? ''));
        $productCode = trim((string)($productCodes[$i] ?? ''));
        $siteProductId = (int)($siteProductIds[$i] ?? 0);
        $unitPrice = (float)($unitPrices[$i] ?? 0);
        if ($siteProductId <= 0 && $serviceName === '' && $productCode === '' && $unitPrice <= 0) {
            continue;
        }
        $lines[] = [
            'line_type' => trim((string)($lineTypes[$i] ?? 'service')),
            'site_product_id' => $siteProductId,
            'service_name' => $serviceName,
            'product_code' => $productCode,
            'description' => trim((string)($descriptions[$i] ?? '')),
            'quantity' => (float)($quantities[$i] ?? 1),
            'unit_price' => $unitPrice,
            'discount_amount' => (float)($discounts[$i] ?? 0),
        ];
    }

    $logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'] ?? '', $_SESSION['role'] ?? '');
    $serviceModule = new ServiceModule($conn, $logger);
    $serviceType = $_POST['service_type'] ?? 'repair';
    $result = $serviceModule->createInvoice([
        'branch_id' => $branchId,
        'service_type' => $serviceType,
        'device_type' => $_POST['device_type'] ?? '',
        'device_brand' => $_POST['device_brand'] ?? '',
        'device_model' => $_POST['device_model'] ?? '',
        'serial_number' => $_POST['serial_number'] ?? '',
        'reported_fault' => $_POST['reported_fault'] ?? '',
        'diagnosis' => $_POST['diagnosis'] ?? '',
        'technician_name' => $_POST['technician_name'] ?? '',
        'repair_status' => $_POST['repair_status'] ?? 'received',
        'warranty_status' => $_POST['warranty_status'] ?? 'out_of_warranty',
        'customer_name' => $_POST['customer_name'] ?? '',
        'customer_phone' => $_POST['customer_phone'] ?? '',
        'customer_email' => $_POST['customer_email'] ?? '',
        'buyer_tin' => $_POST['buyer_tin'] ?? '',
        'buyer_authorization_code' => $_POST['buyer_authorization_code'] ?? '',
        'payment_method' => $_POST['payment_method'] ?? 'cash',
        'notes' => $_POST['notes'] ?? '',
    ], $lines, (int)$_SESSION['user_id']);

    $suffix = empty($result['issues']) ? '' : ' Some EIS checks need attention in the queue.';
    header('Location: index.php?invoice_id=' . (int)$result['invoice_id'] . '&branch_id=' . (int)$branchId . '&type=' . urlencode($serviceType) . '&success=' . urlencode('Service invoice ' . $result['invoice_number'] . ' recorded and queued.' . $suffix));
    exit();
} catch (Throwable $e) {
    error_log('Service action failed: ' . $e->getMessage());
    redirectServices($e->getMessage(), true, isset($branchId) ? $branchId : null, $_POST['service_type'] ?? null);
}
?>