<?php
/**
 * Submit Credit Note to eTIMS API
 * Expects POST: credit_note_id
 */
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';
require_once '../includes/EtimsIntegration.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT', 'BILLING_CLERK', 'FRONT_OFFICE'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$credit_note_id = isset($_POST['credit_note_id']) ? intval($_POST['credit_note_id']) : 0;
if ($credit_note_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid credit note ID']);
    exit();
}

$etims = new EtimsIntegration($conn);
if (!$etims->isEnabled() && !$etims->isMockMode()) {
    echo json_encode(['success' => false, 'message' => 'eTIMS integration is disabled.']);
    exit();
}

$stmt = $conn->prepare("SELECT cn.*, i.invoice_id
                        FROM credit_notes cn
                        INNER JOIN invoices i ON cn.invoice_id = i.invoice_id
                        WHERE cn.credit_note_id = ?");
$stmt->bind_param('i', $credit_note_id);
$stmt->execute();
$cn = $stmt->get_result()->fetch_assoc();
if (!$cn) {
    echo json_encode(['success' => false, 'message' => 'Credit note not found']);
    exit();
}
if ($cn['etims_submitted']) {
    echo json_encode(['success' => false, 'message' => 'Credit note already submitted to eTIMS']);
    exit();
}

$items_sql = "SELECT item_code, item_name, item_class_code, quantity, unit_price, tax_type
              FROM credit_note_items WHERE credit_note_id = ? ORDER BY item_id";
$stmt_i = $conn->prepare($items_sql);
$stmt_i->bind_param('i', $credit_note_id);
$stmt_i->execute();
$items_result = $stmt_i->get_result();
$items = [];
while ($row = $items_result->fetch_assoc()) {
    $items[] = [
        'item_code'      => $row['item_code'],
        'item_name'      => $row['item_name'],
        'item_class_code'=> $row['item_class_code'] ?? '50101502',
        'quantity'       => (float) $row['quantity'],
        'unit_price'     => (float) $row['unit_price'],
        'tax_type'       => $row['tax_type'] ?? 'B',
    ];
}
if (empty($items)) {
    echo json_encode(['success' => false, 'message' => 'Credit note has no line items']);
    exit();
}

// KRA expects originalInvoiceNumber = the invoice number we sent (invoice_id in our flow)
$original_invoice_number = (int) $cn['invoice_id'];
$credit_note_number      = (int) $credit_note_id;
$trader_invoice_no       = $cn['credit_note_number'];

$payload = [
    'original_invoice_number' => $original_invoice_number,
    'credit_note_number'      => $credit_note_number,
    'trader_invoice_no'       => $trader_invoice_no,
    'customer_name'           => $cn['customer_name'],
    'customer_pin'            => $cn['customer_pin'] ?? '',
    'customer_mobile'         => $cn['customer_mobile'] ?? '',
    'customer_address'        => $cn['customer_address'] ?? '',
    'reason'                  => $cn['reason'] ?? 'Refund',
    'items'                   => $items,
];

mysqli_begin_transaction($conn);
try {
    $response = $etims->submitCreditNote($payload);
    if (!$response['success']) {
        throw new Exception($response['message'] ?? 'eTIMS API error');
    }
    $data = $response['data'] ?? [];
    $er = $data['etimsResponse'] ?? [];
    $result_cd = $er['resultCd'] ?? null;
    if ($result_cd !== null && $result_cd !== '000') {
        throw new Exception('KRA rejected credit note (code ' . $result_cd . '): ' . ($er['resultMsg'] ?? 'Unknown'));
    }
    $er_data = $er['data'] ?? [];
    $intrl   = $er_data['intrlData'] ?? $data['intrlData'] ?? $data['receiptSignature'] ?? '';
    $rcpt    = $er_data['rcptSign'] ?? $data['rcptSign'] ?? $data['receiptSignature'] ?? '';
    $e_date  = $data['receiptDate'] ?? date('Y-m-d H:i:s');
    $e_internal = trim($intrl . '|' . $rcpt, '|') ?: null;
    $e_cn_no = $data['creditNoteNumber'] ?? $credit_note_id;

    $upd = "UPDATE credit_notes SET
                etims_submitted = 1,
                etims_credit_number = ?,
                etims_internal_data = ?,
                etims_submission_date = ?
            WHERE credit_note_id = ?";
    $stmt_upd = $conn->prepare($upd);
    $stmt_upd->bind_param('sssi', $e_cn_no, $e_internal, $e_date, $credit_note_id);
    if (!$stmt_upd->execute()) {
        throw new Exception('Failed to update credit note: ' . $conn->error);
    }
    mysqli_commit($conn);
    echo json_encode([
        'success' => true,
        'message' => 'Credit note submitted to eTIMS successfully',
        'data'    => [
            'etims_credit_number' => $e_cn_no,
            'receipt_date'        => $e_date,
            'internal_data'       => $e_internal,
        ],
    ]);
} catch (Exception $e) {
    mysqli_rollback($conn);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
