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

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

// Handle 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 voter_direct_pdf_requests WHERE id=$request_id"));
    
    if ($rec) {
        if ($action == 'success') {
            if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] == UPLOAD_ERR_OK) {
                $file = $_FILES['pdf_file'];
                
                if (strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) != 'pdf') {
                    echo '<script>Swal.fire("Error", "Only PDF!", "error");</script>';
                } else {
                    $fileData = file_get_contents($file['tmp_name']);
                    
                    // Compress if > 300KB
                    if ($file['size'] > 300 * 1024) {
                        $tempInput = sys_get_temp_dir() . '/voter_input_' . time() . '.pdf';
                        $tempOutput = sys_get_temp_dir() . '/voter_output_' . time() . '.pdf';
                        file_put_contents($tempInput, $fileData);
                        
                        $gsPath = '/usr/bin/gs';
                        exec("$gsPath -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$tempOutput $tempInput 2>&1", $output, $returnCode);
                        
                        if ($returnCode === 0 && file_exists($tempOutput) && filesize($tempOutput) > 0) {
                            $fileData = file_get_contents($tempOutput);
                            @unlink($tempOutput);
                        }
                        @unlink($tempInput);
                    }
                    
                    $base64 = "data:application/pdf;base64," . base64_encode($fileData);
                    
                    mysqli_query($ahk_conn, "UPDATE voter_direct_pdf_requests SET 
                        status='Success', pdf_file='" . mysqli_real_escape_string($ahk_conn, $base64) . "', 
                        completed_date=NOW() WHERE id=$request_id");
                    
                    $whamessage = "Dear {$rec['name']},\n\nVoter PDF APPROVED!\n\nOrder: {$rec['order_id']}\nVoter: {$rec['voter_number']}\n\nDownload now!";
                    @send_sms($rec['mobile'], $whamessage);
                    
                    echo '<script>Swal.fire("Success", "Approved!", "success"); setTimeout(function(){ location.reload(); }, 1500);</script>';
                }
            }
        } else if ($action == 'reject') {
            // 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']}'");
            mysqli_query($ahk_conn, "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']}', 'Voter PDF Refund', 'Credit', '{$rec['voter_number']}', 'Voter', {$rec['amount']}, {$rec['amount']}, $old_balance, $new_balance, '{$rec['order_id']}', '{$rec['voter_number']}', 'Refund', NOW(), 'Success')");
            
            mysqli_query($ahk_conn, "UPDATE voter_direct_pdf_requests SET status='Rejected', rejection_reason='$rejection_reason', completed_date=NOW() WHERE id=$request_id");
            
            echo '<script>Swal.fire("Refunded", "Done!", "success"); setTimeout(function(){ location.reload(); }, 1500);</script>';
        }
    }
}

$status = $_GET['status'] ?? 'Pending';
$records = mysqli_query($ahk_conn, "SELECT * FROM voter_direct_pdf_requests WHERE status='$status' ORDER BY id DESC LIMIT 100");

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

<div class="page-wrapper">
    <div class="page-content">
        <div class="card">
            <div class="card-header bg-primary text-white">Voter PDF Admin</div>
            <div class="card-body p-2">
                <div class="btn-group mb-2">
                    <a href="?status=Pending" class="btn btn-sm btn-warning">Pending</a>
                    <a href="?status=Success" class="btn btn-sm btn-success">Success</a>
                    <a href="?status=Rejected" class="btn btn-sm btn-danger">Rejected</a>
                </div>

                <table class="table table-sm">
                    <thead><tr><th>#</th><th>Order ID</th><th>User</th><th>Voter No</th><th>Name</th><th>State</th><th>Amount</th><th>Action</th></tr></thead>
                    <tbody>
                        <?php $sr=1; while($rec = mysqli_fetch_assoc($records)): ?>
                        <tr>
                            <td><?=$sr++?></td>
                            <td><?=$rec['order_id']?></td>
                            <td><?=$rec['username']?></td>
                            <td><?=$rec['voter_number']?></td>
                            <td><?=$rec['voter_name']?></td>
                            <td><?=$rec['state']?></td>
                            <td>₹<?=$rec['amount']?></td>
                            <td>
                                <?php if($rec['status']=='Pending'): ?>
                                <button class="btn btn-sm btn-primary" onclick="$('#act<?=$rec['id']?>').toggle()">⚙️</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php if($rec['status']=='Pending'): ?>
                        <tr id="act<?=$rec['id']?>" style="display:none;">
                            <td colspan="8">
                                <form method="POST" enctype="multipart/form-data" class="p-2 bg-light">
                                    <input type="hidden" name="request_id" value="<?=$rec['id']?>">
                                    <input type="hidden" name="action" value="">
                                    <div class="row">
                                        <div class="col-6">
                                            <input type="file" name="pdf_file" class="form-control-sm" accept=".pdf">
                                            <button type="submit" name="update_status" class="btn btn-success btn-sm mt-1" onclick="this.form.action.value='success'">✅ Approve</button>
                                        </div>
                                        <div class="col-6">
                                            <textarea name="rejection_reason" class="form-control-sm" rows="2"></textarea>
                                            <button type="submit" name="update_status" class="btn btn-danger btn-sm mt-1" onclick="this.form.action.value='reject'">❌ Reject</button>
                                        </div>
                                    </div>
                                </form>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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