<?php
session_start();
if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }
include 'includes/db_connect.php';
include 'includes/header.php';

// --- LOGIC LỌC, TÌM KIẾM VÀ PHÂN TRANG (Giữ nguyên) ---
$records_per_page = 10;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;
$where_clauses = []; $params = []; $types = "";
$search_query = $_GET['q'] ?? '';
if (!empty($search_query)) {
    $where_clauses[] = "(customer_name LIKE ? OR customer_phone LIKE ?)";
    $search_term = "%" . $search_query . "%";
    $params[] = $search_term; $params[] = $search_term; $types .= "ss";
}
$from_date = $_GET['from_date'] ?? ''; $to_date = $_GET['to_date'] ?? '';
if (!empty($from_date) && !empty($to_date)) {
    $where_clauses[] = "DATE(created_at) BETWEEN ? AND ?";
    $params[] = $from_date; $params[] = $to_date; $types .= "ss";
}
$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(' AND ', $where_clauses) : "";
$total_stmt = $conn->prepare("SELECT COUNT(id) as total FROM repairs $where_sql");
if (!empty($types)) $total_stmt->bind_param($types, ...$params);
$total_stmt->execute();
$total_records = $total_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$total_stmt->close();
$data_stmt = $conn->prepare("SELECT * FROM repairs $where_sql ORDER BY created_at DESC LIMIT ? OFFSET ?");
$limit_types = $types . "ii";
$limit_params = array_merge($params, [$records_per_page, $offset]);
if (!empty($types)) $data_stmt->bind_param($limit_types, ...$limit_params);
else $data_stmt->bind_param("ii", $records_per_page, $offset);
$data_stmt->execute();
$repairs = $data_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$data_stmt->close();
?>

<div class="card shadow-sm mb-4">
    <div class="card-body">
        <form action="dashboard.php" method="GET" class="row gx-2 gy-3 align-items-center">
             <div class="col-xl-5 col-lg-4"><input type="text" class="form-control" name="q" placeholder="Tìm theo tên hoặc SĐT..." value="<?php echo htmlspecialchars($search_query); ?>"></div>
            <div class="col-xl-3 col-lg-3 col-sm-6"><input type="date" class="form-control" name="from_date" value="<?php echo htmlspecialchars($from_date); ?>"></div>
            <div class="col-xl-3 col-lg-3 col-sm-6"><input type="date" class="form-control" name="to_date" value="<?php echo htmlspecialchars($to_date); ?>"></div>
            <div class="col-xl-1 col-lg-2 d-grid"><button type="submit" class="btn btn-primary">Lọc</button></div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header bg-white"><h5 class="card-title mb-0"><i class="fa-solid fa-list-check"></i> Lịch Sử Sửa Chữa</h5></div>
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light"><tr class="text-uppercase small">
                <th class="px-3">Khách hàng</th><th>Loại xe</th><th>Hẹn lấy</th><th>Trạng thái CV</th><th class="text-center">Thông báo SMS</th><th class="text-center">Hành động</th>
            </tr></thead>
            <tbody>
                <?php if (empty($repairs)): ?>
                    <tr><td colspan="6" class="text-center text-muted p-5">Không tìm thấy kết quả.</td></tr>
                <?php else: ?>
                    <?php foreach ($repairs as $repair): ?>
                        <tr>
                            <td class="px-3">
                                <div class="fw-bold"><?php echo htmlspecialchars($repair['customer_name']); ?></div>
                                <div class="text-muted small"><?php echo htmlspecialchars($repair['customer_phone']); ?></div>
                            </td>
                            <td><?php echo htmlspecialchars($repair['vehicle_type']); ?></td>
                            <td><?php echo date_format(date_create($repair['pickup_time']), 'H:i d/m/Y'); ?></td>
                            <td>
                                <?php
                                $status = $repair['status'];
                                $badge = '';
                                // --- NÂNG CẤP TOOLTIP ---
                                $tooltip_content = '';
                                if (!empty($repair['repair_details'])) {
                                    $cost = !empty($repair['repair_cost']) ? number_format($repair['repair_cost']) . ' VND' : 'Chưa có';
                                    $tooltip_content = "Nội dung: " . htmlspecialchars($repair['repair_details']) . "\nChi phí: " . $cost;
                                }

                                if ($status == 'đang sửa chữa') $badge = '<span class="badge bg-warning text-dark">Đang sửa</span>';
                                if ($status == 'đã sửa chữa') $badge = '<span class="badge bg-info" data-bs-toggle="tooltip" title="'.$tooltip_content.'">Đã sửa</span>';
                                if ($status == 'đã trả hàng') $badge = '<span class="badge bg-success" data-bs-toggle="tooltip" title="'.$tooltip_content.'">Đã trả</span>';
                                echo $badge;
                                ?>
                            </td>
                            <td class="text-center small">
                                <div>Nhận xe: <?php echo $repair['sms_receipt_status'] == 'đã gửi' ? '<span class="badge rounded-pill bg-success-subtle text-success-emphasis">Đã gửi</span>' : '<span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis">Chưa gửi</span>'; ?></div>
                            </td>
                            <td class="text-center">
                                <div class="btn-group">
                                    <?php if ($status == 'đang sửa chữa'): ?>
                                        <button type="button" class="btn btn-sm btn-outline-success complete-repair-btn" 
                                                data-bs-toggle="modal" data-bs-target="#completeRepairModal"
                                                data-repair-id="<?php echo $repair['id']; ?>" title="Hoàn thành sửa chữa">
                                            <i class="fa-solid fa-check"></i>
                                        </button>
                                    <?php endif; ?>
                                    <a href="edit_repair.php?id=<?php echo $repair['id']; ?>" class="btn btn-sm btn-outline-secondary" title="Sửa"><i class="fa-solid fa-edit"></i></a>
                                    <a href="actions/delete_repair_action.php?id=<?php echo $repair['id']; ?>" class="btn btn-sm btn-outline-danger" title="Xóa" onclick="return confirm('Bạn có chắc muốn xóa?');"><i class="fa-solid fa-trash"></i></a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($total_pages > 1): ?>
    <div class="card-footer bg-white"><nav><ul class="pagination justify-content-center mb-0">
        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
            <li class="page-item <?php if ($i == $current_page) echo 'active'; ?>"><a class="page-link" href="?page=<?php echo $i; ?>&q=<?php echo urlencode($search_query); ?>&from_date=<?php echo $from_date; ?>&to_date=<?php echo $to_date; ?>"><?php echo $i; ?></a></li>
        <?php endfor; ?>
    </ul></nav></div>
    <?php endif; ?>
</div>

<div class="modal fade" id="completeRepairModal" tabindex="-1" aria-labelledby="completeRepairModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="completeRepairModalLabel"><i class="fa-solid fa-check-circle"></i> Xác Nhận Hoàn Thành Sửa Chữa</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="actions/complete_repair_action.php" method="POST">
                <div class="modal-body">
                    <input type="hidden" name="repair_id" id="modal_repair_id">
                    <div class="mb-3">
                        <label for="repair_details" class="form-label">Nội dung đã sửa</label>
                        <textarea class="form-control" id="repair_details" name="repair_details" rows="4" placeholder="VD: Thay săm lốp, tra dầu xích..." required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="mechanic_name" class="form-label">Người sửa</label>
                        <input type="text" class="form-control" id="mechanic_name" name="mechanic_name" placeholder="Nhập tên người sửa" required>
                    </div>
                    <div class="mb-3">
                        <label for="repair_cost" class="form-label">Chi phí (VND)</label>
                        <input type="number" class="form-control" id="repair_cost" name="repair_cost" placeholder="VD: 50000" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button>
                    <button type="submit" class="btn btn-primary">Lưu và Hoàn thành</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Kích hoạt tất cả Tooltip trên trang
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // Xử lý sự kiện khi modal được mở
    var completeRepairModal = document.getElementById('completeRepairModal');
    completeRepairModal.addEventListener('show.bs.modal', function (event) {
        // Nút đã kích hoạt modal
        var button = event.relatedTarget;
        // Lấy repair_id từ thuộc tính data-repair-id của nút
        var repairId = button.getAttribute('data-repair-id');
        // Cập nhật giá trị của trường input ẩn trong form modal
        var modalInput = completeRepairModal.querySelector('#modal_repair_id');
        modalInput.value = repairId;
    });
});
</script>