<?php
require_once("../includes/session.php");
require_once("../includes/config.php");

if (!checkAdmin($udata['type'])) {
    echo '<script>window.location="index.php";</script>';
    exit;
}

// Handle Status Update
if (isset($_POST['update_status'])) {
    $request_id = intval($_POST['request_id']);
    $action = $_POST['action'];
    $rejection_reason = trim($_POST['rejection_reason'] ?? '');
    
    $rec = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT * FROM puc_requests WHERE id=$request_id"));
    
    if ($rec) {
        if ($action == 'success') {
            if (isset($_FILES['receiving_file']) && $_FILES['receiving_file']['error'] == UPLOAD_ERR_OK) {
                $file = $_FILES['receiving_file'];
                $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                
                if (!in_array($fileExtension, ['pdf', 'jpg', 'jpeg', 'png'])) {
                    echo '<script>Swal.fire("Error", "Only PDF/JPG/PNG!", "error");</script>';
                } else {
                    // Read and compress PDF if needed
                    $fileData = file_get_contents($file['tmp_name']);
                    $mimeType = mime_content_type($file['tmp_name']);
                    
                    // Check if PDF and > 300KB
                    if ($fileExtension == 'pdf' && $file['size'] > 300 * 1024) {
                        // Compress PDF using Ghostscript
                        $tempInput = sys_get_temp_dir() . '/input_' . time() . '.pdf';
                        $tempOutput = sys_get_temp_dir() . '/output_' . time() . '.pdf';
                        
                        file_put_contents($tempInput, $fileData);
                        
                        $gsPath = '/usr/bin/gs'; // Adjust path if needed
                        $command = "$gsPath -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$tempOutput $tempInput 2>&1";
                        
                        exec($command, $output, $returnCode);
                        
                        if ($returnCode === 0 && file_exists($tempOutput)) {
                            $compressedSize = filesize($tempOutput);
                            if ($compressedSize < $file['size'] && $compressedSize > 0) {
                                $fileData = file_get_contents($tempOutput);
                            }
                            @unlink($tempOutput);
                        }
                        @unlink($tempInput);
                    }
                    
                    $base64File = "data:" . $mimeType . ";base64," . base64_encode($fileData);
                    
                    mysqli_query($ahk_conn, "UPDATE puc_requests SET 
                        status='Success', receiving_file='" . mysqli_real_escape_string($ahk_conn, $base64File) . "', 
                        completed_date=NOW(), completed_by='{$udata['name']}' 
                        WHERE id=$request_id");
                    
                    $whamessage = "Dear {$rec['name']},\n\nPUC Certificate APPROVED!\n\nOrder ID: {$rec['order_id']}\nVehicle: {$rec['registration_number']}\n\nDownload now!";
                    @send_sms($rec['whatsapp_mobile'], $whamessage);
                    
                    echo '<script>Swal.fire("Success", "Approved!", "success"); setTimeout(function(){ location.reload(); }, 1500);</script>';
                }
            } else {
                echo '<script>Swal.fire("Error", "Upload file!", "error");</script>';
            }
        } else if ($action == 'reject') {
            if (empty($rejection_reason)) {
                echo '<script>Swal.fire("Error", "Reason required!", "error");</script>';
            } else {
                // Refund
                $userInfo = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='{$rec['user_id']}'"));
                $old_balance = floatval($userInfo['balance']);
                $new_balance = $old_balance + floatval($rec['amount']);
                
                mysqli_query($ahk_conn, "UPDATE users SET balance=$new_balance WHERE phone='{$rec['user_id']}'");
                
                $reportSql = "INSERT INTO reports (
                    site_id, user_id, username, name, operator, parent_id, order_id, service, type,
                    account_number, app_type, amount, main_amount, old_balance, new_balance,
                    txn_id, ref_id, description, date_time, status
                ) VALUES (
                    1, '{$rec['user_id']}', '{$rec['username']}', '{$rec['name']}', 'admin', 0,
                    '{$rec['order_id']}', 'PUC Refund', 'Credit', '{$rec['registration_number']}', 'PUC',
                    {$rec['amount']}, {$rec['amount']}, $old_balance, $new_balance, '{$rec['order_id']}', '{$rec['registration_number']}',
                    'PUC Rejected - Refund', NOW(), 'Success'
                )";
                mysqli_query($ahk_conn, $reportSql);
                
                mysqli_query($ahk_conn, "UPDATE puc_requests SET 
                    status='Rejected', rejection_reason='$rejection_reason', completed_date=NOW() 
                    WHERE id=$request_id");
                
                $whamessage = "Dear {$rec['name']},\n\nPUC Request REJECTED.\n\nReason: $rejection_reason\n\nRefund: Rs.{$rec['amount']}";
                @send_sms($rec['whatsapp_mobile'], $whamessage);
                
                echo '<script>Swal.fire("Refunded", "Amount refunded!", "success"); setTimeout(function(){ location.reload(); }, 1500);</script>';
            }
        }
    }
}

$status_filter = $_GET['status'] ?? 'Pending';
$search = $_GET['search'] ?? '';
$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;

$where = "status='$status_filter'";
if (!empty($search)) {
    $where .= " AND (order_id LIKE '%$search%' OR registration_number LIKE '%$search%' OR username LIKE '%$search%')";
}

$records = mysqli_query($ahk_conn, "SELECT * FROM puc_requests WHERE $where ORDER BY id DESC LIMIT $limit");

$pendingCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM puc_requests WHERE status='Pending'"));
$successCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM puc_requests WHERE status='Success'"));
$rejectedCount = mysqli_num_rows(mysqli_query($ahk_conn, "SELECT id FROM puc_requests WHERE status='Rejected'"));

include('../template/ahkweb/header.php');
?>

<style>
.stat-box { padding:15px; border-radius:10px; color:#fff; text-align:center; cursor:pointer; }
.stat-pending { background:linear-gradient(135deg,#f093fb,#f5576c); }
.stat-success { background:linear-gradient(135deg,#4facfe,#00f2fe); }
.stat-rejected { background:linear-gradient(135deg,#fa709a,#fee140); }
.copy-btn { background:#667eea; color:white; border:none; padding:3px 8px; border-radius:5px; font-size:10px; cursor:pointer; }
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row mb-3">
            <div class="col-md-4">
                <div class="stat-box stat-pending" onclick="window.location='?status=Pending'">
                    <h3><?php echo $pendingCount; ?></h3>
                    <p>⏳ Pending</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-box stat-success" onclick="window.location='?status=Success'">
                    <h3><?php echo $successCount; ?></h3>
                    <p>✅ Success</p>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-box stat-rejected" onclick="window.location='?status=Rejected'">
                    <h3><?php echo $rejectedCount; ?></h3>
                    <p>❌ Rejected</p>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-cyan text-white">
                <span><i class="fas fa-leaf"></i> PUC Certificate Management</span>
            </div>
            <div class="card-body p-2">
                <div class="row mb-2">
                    <div class="col-md-6">
                        <form method="GET" class="input-group">
                            <input type="hidden" name="status" value="<?php echo $status_filter; ?>">
                            <input type="text" name="search" class="form-control" placeholder="Search..." value="<?php echo $search; ?>">
                            <button class="btn btn-primary"><i class="fas fa-search"></i></button>
                        </form>
                    </div>
                </div>

                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead class="bg-light">
                            <tr>
                                <th>#</th>
                                <th>Order ID</th>
                                <th>User</th>
                                <th>Vehicle Type</th>
                                <th>Registration</th>
                                <th>Photo</th>
                                <th>Amount</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($records) > 0): ?>
                                <?php $sr = 1; while($rec = mysqli_fetch_assoc($records)): ?>
                                <tr>
                                    <td><?php echo $sr++; ?></td>
                                    <td><code><?php echo $rec['order_id']; ?></code></td>
                                    <td><?php echo $rec['username']; ?><br><small><?php echo $rec['whatsapp_mobile']; ?></small></td>
                                    <td><?php echo $rec['vehicle_type']; ?></td>
                                    <td><code><?php echo $rec['registration_number']; ?></code></td>
                                    <td>
                                        <button class="btn btn-sm btn-info" onclick="viewPhoto(<?php echo $rec['id']; ?>)">
                                            <i class="fas fa-eye"></i> View
                                        </button>
                                    </td>
                                    <td>₹<?php echo $rec['amount']; ?></td>
                                    <td>
                                        <?php if($rec['status']=='Pending'): ?>
                                            <span class="badge badge-warning">Pending</span>
                                        <?php elseif($rec['status']=='Success'): ?>
                                            <span class="badge badge-success">Success</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">Rejected</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if($rec['status']=='Pending'): ?>
                                            <button class="btn btn-sm btn-primary" onclick="toggleAction(<?php echo $rec['id']; ?>)">
                                                <i class="fas fa-cog"></i>
                                            </button>
                                        <?php elseif($rec['status']=='Success'): ?>
                                            <button class="btn btn-sm btn-success" onclick="downloadCert(<?php echo $rec['id']; ?>)">
                                                <i class="fas fa-download"></i>
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                
                                <?php if($rec['status']=='Pending'): ?>
                                <tr id="action_<?php echo $rec['id']; ?>" style="display:none;">
                                    <td colspan="9">
                                        <form method="POST" enctype="multipart/form-data" class="p-3 bg-light">
                                            <input type="hidden" name="request_id" value="<?php echo $rec['id']; ?>">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <h6 class="text-success">✅ Approve</h6>
                                                    <input type="file" name="receiving_file" class="form-control form-control-sm mb-2" accept=".pdf,.jpg,.jpeg,.png" required>
                                                    <button type="submit" name="update_status" value="submit" class="btn btn-success btn-sm" onclick="this.form.action.value='success'">
                                                        <i class="fas fa-check"></i> Approve
                                                    </button>
                                                    <input type="hidden" name="action" value="">
                                                </div>
                                                <div class="col-md-6">
                                                    <h6 class="text-danger">❌ Reject</h6>
                                                    <textarea name="rejection_reason" class="form-control form-control-sm mb-2" rows="2" placeholder="Reason..."></textarea>
                                                    <button type="submit" name="update_status" value="submit" class="btn btn-danger btn-sm" onclick="this.form.action.value='reject'; return confirm('Refund ₹<?php echo $rec['amount']; ?>?')">
                                                        <i class="fas fa-times"></i> Reject & Refund
                                                    </button>
                                                </div>
                                            </div>
                                        </form>
                                    </td>
                                </tr>
                                <?php endif; ?>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr><td colspan="9" class="text-center py-4">No Records</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Photo Modal -->
<div class="modal fade" id="photoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Vehicle Photo</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body text-center">
                <img id="vehiclePhoto" src="" style="max-width:100%;">
            </div>
        </div>
    </div>
</div>

<script>
function toggleAction(id) {
    var row = document.getElementById('action_' + id);
    row.style.display = (row.style.display === 'none') ? 'table-row' : 'none';
}

function viewPhoto(id) {
    fetch('get_puc_photo.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                document.getElementById('vehiclePhoto').src = data.photo;
                $('#photoModal').modal('show');
            }
        });
}

function downloadCert(id) {
    window.open('download_puc_cert.php?id=' + id, '_blank');
}
</script>

<style>.bg-cyan{background:linear-gradient(90deg,#00bcd4,#00acc1)!important;}</style>

<?php include('../admin/footers.php'); ?>