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

$pdo = getDB();

$where = '';
$params = [];

// Filters
if (!empty($_GET['status'])) {
    $where .= ' AND rj.repair_status = ?';
    $params[] = $_GET['status'];
}
if (!empty($_GET['technician'])) {
    $where .= ' AND rj.assigned_technician_id = ?';
    $params[] = (int)$_GET['technician'];
}
if (!empty($_GET['date_from'])) {
    $where .= ' AND DATE(rj.created_at) >= ?';
    $params[] = $_GET['date_from'];
}
if (!empty($_GET['date_to'])) {
    $where .= ' AND DATE(rj.created_at) <= ?';
    $params[] = $_GET['date_to'];
}
if (!empty($_GET['due_only'])) {
    $where .= ' AND rj.due_amount > 0';
}

$stmt = $pdo->prepare("
    SELECT rj.*, c.name as customer_name, c.phone as customer_phone, u.name as technician_name
    FROM repair_jobs rj
    LEFT JOIN customers c ON rj.customer_id = c.id
    LEFT JOIN users u ON rj.assigned_technician_id = u.id
    WHERE 1=1 $where
    ORDER BY rj.id DESC
");
$stmt->execute($params);
$jobs = $stmt->fetchAll();

$technicians = $pdo->query("SELECT id, name FROM users WHERE role_id = 4 AND status = 1 ORDER BY name")->fetchAll();
$statuses = ['Received','Checking','Waiting for Customer Approval','Waiting for Parts','Repairing','Completed','Delivered','Cancelled','Cannot Repair'];

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-tools me-2"></i>Repair Jobs</h4>
            <div>
                <a href="add_repair_job.php" class="btn btn-primary"><i class="fas fa-plus me-1"></i>New Job Card</a>
                <a href="technician_panel.php" class="btn btn-info"><i class="fas fa-user-cog me-1"></i>Technician Panel</a>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card">
            <div class="card-body">
                <form method="GET" class="row g-2 mb-3 no-print">
                    <div class="col-auto">
                        <select name="status" class="form-select form-select-sm">
                            <option value="">All Statuses</option>
                            <?php foreach ($statuses as $s): ?>
                            <option value="<?= $s ?>" <?= (($_GET['status'] ?? '') == $s) ? 'selected' : '' ?>><?= $s ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-auto">
                        <select name="technician" class="form-select form-select-sm">
                            <option value="">All Technicians</option>
                            <?php foreach ($technicians as $t): ?>
                            <option value="<?= $t['id'] ?>" <?= (($_GET['technician'] ?? '') == $t['id']) ? 'selected' : '' ?>><?= htmlspecialchars($t['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-auto">
                        <input type="date" name="date_from" class="form-control form-control-sm" value="<?= htmlspecialchars($_GET['date_from'] ?? '') ?>" placeholder="From">
                    </div>
                    <div class="col-auto">
                        <input type="date" name="date_to" class="form-control form-control-sm" value="<?= htmlspecialchars($_GET['date_to'] ?? '') ?>" placeholder="To">
                    </div>
                    <div class="col-auto">
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" name="due_only" value="1" id="dueOnly" <?= isset($_GET['due_only']) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="dueOnly">Due Only</label>
                        </div>
                    </div>
                    <div class="col-auto">
                        <button type="submit" class="btn btn-sm btn-primary"><i class="fas fa-filter"></i> Filter</button>
                        <a href="repair_jobs.php" class="btn btn-sm btn-secondary"><i class="fas fa-times"></i> Reset</a>
                    </div>
                </form>

                <div class="table-responsive">
                    <table id="repairJobsTable" class="table table-hover datatable">
                        <thead>
                            <tr>
                                <th>Job #</th>
                                <th>Customer</th>
                                <th>Device</th>
                                <th>Technician</th>
                                <th>Priority</th>
                                <th>Status</th>
                                <th>Amount</th>
                                <th>Paid</th>
                                <th>Due</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($jobs as $j): ?>
                            <tr class="<?= $j['priority'] == 'Urgent' ? 'table-warning' : '' ?>">
                                <td><strong><?= htmlspecialchars($j['job_no']) ?></strong></td>
                                <td><?= htmlspecialchars($j['customer_name'] ?? '-') ?><br><small class="text-muted"><?= htmlspecialchars($j['customer_phone'] ?? '') ?></small></td>
                                <td>
                                    <?= htmlspecialchars($j['device_brand'] ?? '') ?> <?= htmlspecialchars($j['device_model'] ?? '') ?>
                                    <?php if (!empty($j['device_imei'])): ?><br><code><?= htmlspecialchars($j['device_imei']) ?></code><?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($j['technician_name'] ?? 'Unassigned') ?></td>
                                <td><?= $j['priority'] == 'Urgent' ? '<span class="badge bg-danger">Urgent</span>' : '<span class="badge bg-secondary">Normal</span>' ?></td>
                                <td><?= getStatusBadge($j['repair_status']) ?></td>
                                <td class="fw-bold"><?= formatCurrency($j['final_amount']) ?></td>
                                <td class="text-success"><?= formatCurrency($j['paid_amount']) ?></td>
                                <td class="<?= $j['due_amount'] > 0 ? 'text-danger fw-bold' : '' ?>"><?= formatCurrency($j['due_amount']) ?></td>
                                <td><?= formatDate($j['created_at'], 'Y-m-d') ?></td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-secondary dropdown-toggle" data-bs-toggle="dropdown"><i class="fas fa-cog"></i></button>
                                        <ul class="dropdown-menu">
                                            <li><a class="dropdown-item" href="view_repair_job.php?id=<?= $j['id'] ?>"><i class="fas fa-eye me-1"></i> View</a></li>
                                            <li><a class="dropdown-item" href="edit_repair_job.php?id=<?= $j['id'] ?>"><i class="fas fa-edit me-1"></i> Edit</a></li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li><a class="dropdown-item" href="repair_invoice.php?id=<?= $j['id'] ?>"><i class="fas fa-file-invoice me-1"></i> Invoice</a></li>
                                            <li><a class="dropdown-item" href="print_repair_invoice.php?id=<?= $j['id'] ?>" target="_blank"><i class="fas fa-print me-1"></i> Print</a></li>
                                            <li><a class="dropdown-item" href="repair_payment.php?job_id=<?= $j['id'] ?>"><i class="fas fa-money-bill me-1"></i> Payment</a></li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
