<?php
/**
 * Fix receipts that show only ~4 items because repair was truncated (VARCHAR(255)).
 * Load a job by Sale ID (e.g. IV-SG00125), edit the repair/items text, save.
 * Requires login.
 */
require_once __DIR__ . '/db.php';

if (empty($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

$pdo = $pdo ?? null;
if (!$pdo) {
    die("Database connection not available.");
}

$message = '';
$job = null;
$jobIdInput = trim((string)($_GET['job_id'] ?? $_POST['job_id'] ?? ''));

// Calculate total from repair string (same logic as receipt.php) so dashboard shows correct total
function calculateTotalFromRepair($repair) {
    $total = 0;
    $rawItems = explode(' || ', $repair);
    foreach ($rawItems as $rawItem) {
        $clean = trim(preg_replace('/\[W:.*?\]/', '', $rawItem));
        $clean = trim(preg_replace('/\[SN:.*?\]/', '', $clean));
        if (preg_match('/\([xX](\d+)\)\s*@\s*([0-9.]+)/', $clean, $m)) {
            $total += (float)$m[1] * (float)$m[2];
        }
    }
    return round($total, 2);
}

// Update repair and price (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $jobIdInput !== '') {
    $repair = trim((string)($_POST['repair'] ?? ''));
    $id = (int)($_POST['id'] ?? 0); // internal row id
    if ($id > 0) {
        $newTotal = calculateTotalFromRepair($repair);
        $stmt = $pdo->prepare("UPDATE jobs SET repair = ?, price = ? WHERE id = ?");
        $stmt->execute([$repair, $newTotal, $id]);
        $message = 'Updated repair and total (RM ' . number_format($newTotal, 2) . '). <a href="receipt.php?id=' . urlencode($jobIdInput) . '">View receipt</a> | <a href="dashboard.php">Dashboard</a>';
        $jobIdInput = '';
    }
}

// Load job by job_id or invoice_id (GET or after save)
if ($jobIdInput !== '') {
    $stmt = $pdo->prepare("SELECT id, job_id, invoice_id, repair, customer, date FROM jobs WHERE job_id = ? OR invoice_id = ? LIMIT 1");
    $stmt->execute([$jobIdInput, $jobIdInput]);
    $job = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$job) {
        $message = 'No job found for: ' . htmlspecialchars($jobIdInput);
        $job = null;
    }
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Fix receipt items</title>
    <style>
        body { font-family: sans-serif; max-width: 800px; margin: 20px auto; padding: 0 15px; }
        input[type="text"] { width: 200px; padding: 6px; }
        textarea { width: 100%; min-height: 200px; padding: 8px; box-sizing: border-box; font-family: monospace; font-size: 12px; }
        .box { border: 1px solid #ccc; padding: 15px; margin: 15px 0; background: #f9f9f9; }
        button { padding: 8px 16px; cursor: pointer; }
        .hint { font-size: 0.9rem; color: #666; margin-top: 8px; }
        a { color: #06c; }
    </style>
</head>
<body>
    <h1>Fix receipt items (truncated)</h1>
    <p>Use this to fix receipts like IV-SG00125 / IV-SG00126 that show only ~4 items because the item list was cut off at 255 characters. Paste or type the <strong>full</strong> item list in the same format (each item: <code>Name (xqty) @ price [W: warranty]</code>, separated by <code> || </code>).</p>

    <?php if ($message !== '') echo '<p class="box">' . $message . '</p>'; ?>

    <div class="box">
        <form method="get">
            <label>Sale / Job ID: <input type="text" name="job_id" value="<?php echo htmlspecialchars($jobIdInput); ?>" placeholder="e.g. IV-SG00125"></label>
            <button type="submit">Load</button>
        </form>
    </div>

    <?php if ($job): ?>
    <div class="box">
        <p><strong><?php echo htmlspecialchars($job['job_id']); ?></strong> — <?php echo htmlspecialchars($job['customer']); ?> — <?php echo htmlspecialchars($job['date']); ?></p>
        <p class="hint">Current length: <?php echo strlen($job['repair'] ?? ''); ?> characters. Edit below and Save to update the receipt.</p>
        <form method="post">
            <input type="hidden" name="id" value="<?php echo (int)$job['id']; ?>">
            <input type="hidden" name="job_id" value="<?php echo htmlspecialchars($job['job_id']); ?>">
            <label>Repair / items (full list):</label><br>
            <textarea name="repair" placeholder="Item A (x1) @ 10.00 [W: 1 Month] || Item B (x2) @ 5.00 [W: No Warranty] || ..."><?php echo htmlspecialchars($job['repair'] ?? ''); ?></textarea><br>
            <button type="submit">Save</button>
        </form>
    </div>
    <?php endif; ?>

    <p><a href="dashboard.php">Back to dashboard</a></p>
</body>
</html>
