<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

ob_start();
if (session_status() === PHP_SESSION_NONE) { 
    session_start(); 
}

// Core framework configurations
require_once('../titancore/titanconfig.php');

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

// Inject standard layout shell & enforce charset compliance
require_once('../titancore/titanheader.php');
mysqli_set_charset($conn, "utf8mb4");

// Dynamic contextual payload mapping
$uid_fetch = $_SESSION['user_id'];
$user_query = $conn->query("SELECT * FROM users WHERE id='$uid_fetch'");
$u_row = $user_query->fetch_assoc() ?? [];
$u_name = $u_row['user_name'] ?? $_SESSION['user_name'] ?? 'User';
$u_mobile = $u_row['phone'] ?? '0000000000';

$msg = '';
$msg_type = 'info';

// Handle PUCC Certificate Document Upload
if (isset($_POST['upload_cert'])) {
    $id = intval($_POST['history_id']);
    $file = $_FILES['certificate']['name'];
    $upload_dir = "../uploads/pucc/";

    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $allowed_types = ['jpg', 'jpeg', 'png', 'webp', 'pdf'];

    if (!in_array($ext, $allowed_types)) {
        $msg = "Only JPG, JPEG, PNG, WEBP, and PDF files are allowed.";
        $msg_type = "error";
    } else {
        // Clean up filename to prevent broken paths/DB issues
        $safe_basename = time() . "_" . preg_replace("/[^a-zA-Z0-9._-]/", "_", basename($file));
        $file_path = $upload_dir . $safe_basename;
        
        // Relative path saved to database matching your framework style
        $db_path = "uploads/pucc/" . $safe_basename; 

        if (move_uploaded_file($_FILES['certificate']['tmp_name'], $file_path)) {
            
            // NOTE: If your actual DB column is named 'certificate', change "SET cert = ?" to "SET certificate = ?"
            $stmt = $conn->prepare("UPDATE cpuchistory SET cert = ?, status = 2, mstatus = 1 WHERE id = ?");
            $stmt->bind_param("si", $db_path, $id);
            
            if ($stmt->execute()) {
                $msg = "PUC Certificate uploaded successfully!";
                $msg_type = "success";
            } else {
                $msg = "Database update failed: " . $stmt->error;
                $msg_type = "error";
            }
            $stmt->close();
        } else {
            $msg = "Error moving uploaded file.";
            $msg_type = "error";
        }
    }
}

// Handle Manual Status Updates
if (isset($_POST['update_status'])) {
    $id = intval($_POST['history_id']);
    $status = intval($_POST['status']);
    $mstatus = ($status === 2 || $status === 3) ? 1 : 0;

    $stmt = $conn->prepare("UPDATE cpuchistory SET status = ?, mstatus = ? WHERE id = ?");
    $stmt->bind_param("iii", $status, $mstatus, $id);
    if ($stmt->execute()) {
        $msg = "Status updated successfully!";
        $msg_type = "success";
    } else {
        $msg = "Failed to update record status.";
        $msg_type = "error";
    }
    $stmt->close();
}

// Pull active queue items where status is Pending (0) or Inprocess (1)
$result = $conn->query("SELECT * FROM cpuchistory WHERE status IN (0, 1) ORDER BY id DESC");
$total_tickets = $result ? $result->num_rows : 0;
?>

<div class="container-fluid px-4 py-4">
    <div class="row mb-4">
        <div class="col-12">
            <div class="card bg-white shadow-sm border border-light-subtle">
                <div class="row gx-0 align-items-center p-3">
                    <div class="col-auto d-flex align-items-center">
                        <div class="p-3 bg-warning-subtle rounded-circle me-3 d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                            <span class="fas fa-smog text-warning fs-4"></span>
                        </div>
                        <div>
                            <h6 class="text-muted small uppercase mb-0">Active Queue</h6>
                            <h4 class="text-dark fw-bold mb-0"><?php echo $total_tickets; ?> Processing Tickets</h4>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm border-0 border-top border-4 border-primary">
                <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold"><i class="fas fa-list me-2 text-primary"></i>PUCC Pending Applications Operations</h5>
                    <span class="badge bg-primary px-2.5 py-2 uppercase">Action Required</span>
                </div>
                <div class="card-body p-0 bg-white">
                    <div class="table-responsive">
                        <table class="table table-striped table-hover align-middle mb-0" style="font-size: 0.9rem;">
                            <thead class="table-light text-secondary">
                                <tr>
                                    <th class="ps-3 py-3 text-center" style="width: 80px;">ID</th>
                                    <th>Vehicle No.</th>
                                    <th>Transaction ID</th>
                                    <th>Customer Contact</th>
                                    <th class="text-center">Raw Attachment</th>
                                    <th class="text-center">Certificate</th>
                                    <th class="text-center">Status</th>
                                    <th style="min-width: 260px;">Fulfill Document</th>
                                    <th class="pe-3" style="min-width: 170px;">Change Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if ($result && $total_tickets > 0): ?>
                                <?php while ($row = $result->fetch_assoc()): ?>
                                    <tr>
                                        <td class="ps-3 py-3 text-center fw-bold text-muted">#<?php echo $row['id']; ?></td>
                                        <td class="fw-bold text-uppercase text-dark font-monospace"><?php echo htmlspecialchars($row['number'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td class="font-monospace text-secondary"><?php echo htmlspecialchars($row['tnsid'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td class="font-monospace text-secondary"><?php echo htmlspecialchars($row['custno'] ?? 'N/A', ENT_QUOTES, 'UTF-8'); ?></td>
                                        <td class="text-center">
                                            <?php if (!empty($row['backimage'])): ?>
                                                <a class="btn btn-link btn-sm p-0 fw-bold fs--1" href="../<?php echo htmlspecialchars($row['backimage'], ENT_QUOTES, 'UTF-8'); ?>" target="_blank">
                                                    <span class="fas fa-image me-1"></span>View Image
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted small">No Upload</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <?php 
                                            $cert_file = $row['cert'] ?? $row['certificate'] ?? '';
                                            if (!empty($cert_file)): 
                                            ?>
                                                <a class="btn btn-link btn-sm p-0 fw-bold text-success fs--1" href="../<?php echo htmlspecialchars($cert_file, ENT_QUOTES, 'UTF-8'); ?>" target="_blank">
                                                    <span class="fas fa-file-pdf me-1"></span>View Document
                                                </a>
                                            <?php else: ?>
                                                <span class="badge bg-light text-secondary border border-light-subtle">Empty</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <?php
                                                $status_val = intval($row['status'] ?? 0);
                                                if ($status_val === 0) {
                                                    echo '<span class="badge bg-warning text-dark px-2 py-1.5 uppercase">PENDING</span>';
                                                } elseif ($status_val === 1) {
                                                    echo '<span class="badge bg-info px-2 py-1.5 uppercase">PROCESSING</span>';
                                                } elseif ($status_val === 2) {
                                                    echo '<span class="badge bg-success px-2 py-1.5 uppercase">COMPLETE</span>';
                                                } else {
                                                    echo '<span class="badge bg-danger px-2 py-1.5 uppercase">REJECTED</span>';
                                                }
                                            ?>
                                        </td>
                                        <td>
                                            <form method="POST" enctype="multipart/form-data" class="d-flex align-items-center gap-1 px-1">
                                                <input type="file" name="certificate" accept="image/*,application/pdf" required class="form-control form-control-sm py-1 shadow-sm">
                                                <input type="hidden" name="history_id" value="<?php echo $row['id']; ?>">
                                                <button type="submit" name="upload_cert" class="btn btn-success btn-sm px-2 shadow-sm" title="Upload & Fulfill">
                                                    <span class="fas fa-upload"></span>
                                                </button>
                                            </form>
                                        </td>
                                        <td class="pe-3">
                                            <form method="POST" class="d-flex align-items-center gap-1 px-1">
                                                <select name="status" class="form-select form-select-sm py-1 shadow-sm font-sans-serif" style="font-size: 0.85rem;">
                                                    <option value="0" <?php echo ($status_val === 0) ? 'selected' : ''; ?>>Pending</option>
                                                    <option value="1" <?php echo ($status_val === 1) ? 'selected' : ''; ?>>Inprocess</option>
                                                    <option value="2" <?php echo ($status_val === 2) ? 'selected' : ''; ?>>Complete</option>
                                                    <option value="3" <?php echo ($status_val === 3) ? 'selected' : ''; ?>>Reject Record</option>
                                                </select>
                                                <input type="hidden" name="history_id" value="<?php echo $row['id']; ?>">
                                                <button type="submit" name="update_status" class="btn btn-primary btn-sm px-2 shadow-sm">
                                                    Update
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="9" class="text-center py-5 text-muted fst-italic bg-light">
                                        <i class="fas fa-check-circle text-success fs-3 d-block mb-2"></i> No active applications inside processing queue.
                                    </td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<?php if (!empty($msg)): ?>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        Swal.fire({
            icon: '<?php echo $msg_type; ?>',
            title: '<?php echo ($msg_type === "success") ? "Action Succeeded" : "Notice"; ?>',
            text: <?php echo json_encode($msg); ?>,
            confirmButtonColor: '#2c7be5'
        }).then(() => {
            window.location.href = window.location.pathname;
        });
    });
</script>
<?php endif; ?>

<?php 
require_once('../titancore/TitanFooter.php'); 
ob_end_flush();
?>