<?php
require_once __DIR__ . '/../../classes/CustomerService.php';
require_once __DIR__ . '/../../classes/Logger.php';
include '../../includes/header.php';

$logger       = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$service      = new CustomerService($conn, $logger);
$isAdmin      = $auth->isSuperAdmin($_SESSION['user_id']) || $auth->isWarehousePersonnel($_SESSION['user_id']);
$isController = $auth->isController($_SESSION['user_id']);
$canSeeAll    = $isAdmin || $isController;
$branchId     = $canSeeAll ? null : $auth->getUserBranch($_SESSION['user_id']);

$requests   = $service->getRequests($branchId);
$selectedId = isset($_GET['request_id']) ? (int)$_GET['request_id'] : 0;
$selected   = $selectedId ? $service->getById($selectedId) : null;
$notes      = $selectedId ? $service->getNotes($selectedId) : [];
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <h2 class="mb-1">Customer Claims &amp; Service</h2>
            <p class="text-muted mb-0">Track receipt-linked claims, warranties, service requests, communication, and resolution.</p>
        </div>
        <?php if (!$isController): ?>
            <a href="create.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i> New Claim</a>
        <?php endif; ?>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <?php echo htmlspecialchars($_GET['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body table-responsive">
            <table class="table table-striped align-middle" id="serviceTable">
                <thead>
                    <tr>
                        <th>Request</th>
                        <th>Receipt</th>
                        <th>Customer</th>
                        <th>Subject</th>
                        <th>Item</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Delivery Date</th>
                        <th>Updated</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($requests as $r): ?>
                        <tr>
                            <td>
                                <strong><?php echo htmlspecialchars($r['request_no']); ?></strong><br>
                                <small class="text-muted"><?php echo htmlspecialchars(ucfirst($r['request_type'])); ?></small>
                            </td>
                            <td>
                                <?php if (!empty($r['receipt_number'])): ?>
                                    <a href="../tracking/txn_tracking.php?transaction_id=<?php echo urlencode($r['receipt_number']); ?>">
                                        <?php echo htmlspecialchars($r['receipt_number']); ?>
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted">N/A</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo htmlspecialchars($r['customer_name']); ?><br>
                                <small class="text-muted"><?php echo htmlspecialchars($r['customer_phone'] ?? ''); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($r['subject']); ?></td>
                            <td><?php echo htmlspecialchars(trim(($r['unique_code'] ?? '') . ' ' . ($r['item_name'] ?? '') . ' - ' . ($r['item_details'] ?? '')) ?: 'N/A'); ?></td>
                            <td><span class="badge bg-secondary"><?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $r['status']))); ?></span></td>
                            <td><?php echo htmlspecialchars(ucfirst($r['priority'])); ?></td>
                            <td>
                                <?php if (!empty($r['delivery_date'])): ?>
                                    <span class="text-primary fw-semibold"><?php echo htmlspecialchars(date('d M Y', strtotime($r['delivery_date']))); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <td><small><?php echo htmlspecialchars($r['updated_at']); ?></small></td>
                            <td><a class="btn btn-sm btn-outline-primary" href="?request_id=<?php echo (int)$r['request_id']; ?>">Open</a></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($selected): ?>

    <?php
        $receiptUrl = !empty($selected['receipt_number'])
            ? '../tracking/txn_tracking.php?transaction_id=' . urlencode($selected['receipt_number'])
            : null;
        $deliveryDateFmt = !empty($selected['delivery_date'])
            ? date('d M Y', strtotime($selected['delivery_date']))
            : null;
        $deliveryDateInput = !empty($selected['delivery_date'])
            ? date('Y-m-d', strtotime($selected['delivery_date']))
            : '';
    ?>

    <div class="card mt-4">
        <div class="card-header d-flex justify-content-between align-items-center">
            <strong><?php echo htmlspecialchars($selected['request_no']); ?> — <?php echo htmlspecialchars($selected['subject']); ?></strong>
            <?php if ($receiptUrl): ?>
                <a href="<?php echo htmlspecialchars($receiptUrl); ?>" target="_blank" class="btn btn-sm btn-outline-dark">
                    <i class="fas fa-receipt me-1"></i> View Receipt
                </a>
            <?php endif; ?>
        </div>
        <div class="card-body">

            <!-- ── Claim summary ── -->
            <div class="row g-3 mb-4">
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Receipt</div>
                    <?php if ($receiptUrl): ?>
                        <a href="<?php echo htmlspecialchars($receiptUrl); ?>" target="_blank">
                            <?php echo htmlspecialchars($selected['receipt_number']); ?>
                        </a>
                    <?php else: ?>
                        <span class="text-muted">N/A</span>
                    <?php endif; ?>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Customer</div>
                    <div class="fw-semibold"><?php echo htmlspecialchars($selected['customer_name']); ?></div>
                    <div class="text-muted small"><?php echo htmlspecialchars($selected['customer_phone'] ?? ''); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Branch / Item</div>
                    <div><?php echo htmlspecialchars($selected['branch_name'] ?? 'N/A'); ?></div>
                    <div class="text-muted small"><?php echo htmlspecialchars(trim(($selected['unique_code'] ?? '') . ' ' . ($selected['item_name'] ?? '') . ' - ' . ($selected['item_details'] ?? '')) ?: 'N/A'); ?></div>
                </div>
                <div class="col-md-3">
                    <div class="text-muted small text-uppercase fw-bold mb-1">Finish / Delivery Date</div>
                    <?php if ($deliveryDateFmt): ?>
                        <div class="fw-semibold text-primary"><?php echo htmlspecialchars($deliveryDateFmt); ?></div>
                    <?php else: ?>
                        <div class="text-muted">Not set</div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($selected['description'] ?? ''): ?>
            <div class="mb-4">
                <div class="text-muted small text-uppercase fw-bold mb-1">Description</div>
                <div class="border rounded p-3 bg-light"><?php echo nl2br(htmlspecialchars($selected['description'])); ?></div>
            </div>
            <?php endif; ?>

            <?php if ($isController): ?>
            <!-- ── Controller: delivery date form only ── -->
            <form method="POST" action="update.php" class="row g-3 mb-4">
                <input type="hidden" name="request_id" value="<?php echo (int)$selected['request_id']; ?>">
                <div class="col-md-4">
                    <label class="form-label fw-bold">Finish / Delivery Date</label>
                    <input type="date" name="delivery_date" class="form-control"
                           value="<?php echo htmlspecialchars($deliveryDateInput); ?>">
                </div>
                <div class="col-md-8">
                    <label class="form-label fw-bold">Note <span class="text-muted fw-normal">(optional)</span></label>
                    <input type="text" name="note" class="form-control" placeholder="Add an internal note…">
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-calendar-check me-1"></i> Update Delivery Date
                    </button>
                </div>
            </form>

            <?php else: ?>
            <!-- ── Admin / branch: full update form ── -->
            <form method="POST" action="update.php" class="row g-3 mb-4">
                <input type="hidden" name="request_id" value="<?php echo (int)$selected['request_id']; ?>">
                <div class="col-md-3">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <?php foreach (['open','in_progress','waiting_customer','approved','rejected','resolved','closed'] as $st): ?>
                            <option value="<?php echo $st; ?>" <?php echo $selected['status'] === $st ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $st))); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Finish / Delivery Date</label>
                    <input type="date" name="delivery_date" class="form-control"
                           value="<?php echo htmlspecialchars($deliveryDateInput); ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Resolution</label>
                    <input type="text" name="resolution" class="form-control"
                           value="<?php echo htmlspecialchars($selected['resolution'] ?? ''); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Note Visibility</label>
                    <select name="visibility" class="form-select">
                        <option value="internal">Internal</option>
                        <option value="customer">Customer</option>
                    </select>
                </div>
                <div class="col-md-9">
                    <label class="form-label">Add Note</label>
                    <textarea name="note" rows="2" class="form-control"></textarea>
                </div>
                <div class="col-12">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save me-1"></i> Update Request
                    </button>
                </div>
            </form>
            <?php endif; ?>

            <!-- ── Notes ── -->
            <h6 class="fw-bold mb-2">Notes</h6>
            <?php if (!$notes): ?>
                <p class="text-muted">No notes yet.</p>
            <?php else: ?>
                <ul class="list-group">
                    <?php foreach ($notes as $note): ?>
                        <li class="list-group-item">
                            <span class="badge bg-light text-dark border me-1"><?php echo htmlspecialchars($note['visibility']); ?></span>
                            <?php echo nl2br(htmlspecialchars($note['note'])); ?><br>
                            <small class="text-muted"><?php echo htmlspecialchars($note['username'] ?? 'Unknown'); ?>, <?php echo htmlspecialchars($note['created_at']); ?></small>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>

        </div>
    </div>

    <?php endif; ?>
</div>

<script>
    new DataTable('#serviceTable');
</script>

<?php include '../../includes/footer.php'; ?>
