<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('warranty_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_claim') {
    $warranty_id = (int)$_POST['warranty_id'];
    $issue = trim($_POST['problem_description']);
    $decision = trim($_POST['decision'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    if ($warranty_id && $issue) {
        $claim_no = generateClaimNo();
        $stmt = $pdo->prepare("INSERT INTO warranty_claims (warranty_record_id, claim_no, claim_date, issue_description, decision_note, claim_status) VALUES (?,?,CURDATE(),?,?,'Pending')");
        $stmt->execute([$warranty_id, $claim_no, $issue, $notes]);
        $pdo->prepare("UPDATE warranty_records SET warranty_status='Claimed' WHERE id=?")->execute([$warranty_id]);
        logActivity('Created Warranty Claim', 'Warranty', $pdo->lastInsertId());
        $_SESSION['success'] = "Claim #$claim_no created.";
    }
    header('Location: warranty_claims.php'); exit;
}

$claims = $pdo->query("
    SELECT wc.*, w.warranty_type, w.warranty_start_date, w.warranty_end_date, p.product_name as product_name, c.name as customer_name, c.phone as customer_phone
    FROM warranty_claims wc
    JOIN warranty_records w ON wc.warranty_record_id = w.id
    LEFT JOIN products p ON w.product_id = p.id
    LEFT JOIN customers c ON w.customer_id = c.id
    ORDER BY wc.id DESC
")->fetchAll();

$warranties_active = $pdo->query("SELECT w.*, p.product_name as product_name, c.name as customer_name FROM warranty_records w LEFT JOIN products p ON w.product_id = p.id LEFT JOIN customers c ON w.customer_id = c.id WHERE w.warranty_status = 'Active' ORDER BY w.id DESC")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Warranty Claims</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#claimModal"><i class="fas fa-plus me-1"></i>New Claim</button>
        </div>
        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="warrantyClaimsTable" class="table table-hover datatable">
                        <thead><tr><th>Claim #</th><th>Warranty Type</th><th>Customer</th><th>Product</th><th>Date</th><th>Decision</th><th>Status</th></tr></thead>
                        <tbody>
                            <?php foreach ($claims as $cl): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($cl['claim_no']) ?></strong></td>
                                <td><span class="badge bg-<?= $cl['warranty_type'] == 'product' ? 'primary' : 'info' ?>"><?= $cl['warranty_type'] ?></span></td>
                                <td><?= htmlspecialchars($cl['customer_name'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($cl['product_name'] ?? '-') ?></td>
                                <td><?= formatDate($cl['claim_date']) ?></td>
                                <td><?= getStatusBadge($cl['claim_status']) ?></td>
                                <td><?= getStatusBadge($cl['claim_status']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="claimModal" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="add_claim">
            <div class="modal-header"><h5 class="modal-title">New Warranty Claim</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Warranty Record *</label>
                    <select name="warranty_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php foreach ($warranties_active as $wa): ?>
                        <option value="<?= $wa['id'] ?>"><?= htmlspecialchars($wa['product_name'] ?? '-') ?> - <?= htmlspecialchars($wa['customer_name'] ?? '-') ?> (Exp: <?= formatDate($wa['warranty_end_date']) ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Issue Description *</label>
                    <textarea name="problem_description" class="form-control" rows="3" required></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-primary">Submit Claim</button>
            </div>
        </form>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
