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

if (!in_array($udata['type'], ['Master Distributor', 'Distributor', 'Retailer', 'admin'])) {
    require_once("404.php");
    exit;
}

if ($udata['voter_direct_pdf_service'] != "YES") {
    echo '<script>
        Swal.fire("Access Denied", "Voter Direct PDF service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$show_popup = false;
$popup_order_id = '';
$popup_voter_number = '';

if (isset($_POST['submit'])) {
    $voterNumber = strtoupper(trim($_POST['voterNumber']));
    $voterName = trim($_POST['voterName']);
    $state = trim($_POST['state']);
    $otherState = trim($_POST['otherState'] ?? '');
    
    if ($state === 'Other State' && !empty($otherState)) {
        $state = $otherState;
    }

    if (!empty($voterNumber) && !empty($voterName) && !empty($state)) {
        $amount = floatval($udata['voter_direct_pdf_fee'] ?? 40);
        $old_balance = $udata['balance'];
        $new_balance = $old_balance - $amount;

        if ($udata['balance'] >= $amount) {
            $order_id = 'VOTER' . time() . rand(1000, 9999);
            
            $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
            
            if ($updateSuccess) {
                // Insert transaction report
                $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, '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['type']}', 0,
                    '$order_id', 'Voter Direct PDF', 'Debit', '$voterNumber', 'Voter Direct PDF',
                    $amount, $amount, $old_balance, $new_balance, '$order_id', '$voterNumber',
                    'Rs.$amount debited for Voter PDF Download', NOW(), 'Success'
                )";
                mysqli_query($ahk_conn, $reportSql);
                
                // Insert voter request
                $requestSql = "INSERT INTO voter_direct_pdf_requests (
                    user_id, username, name, mobile, order_id, voter_number, voter_name, state, amount, status, request_date
                ) VALUES (
                    '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                    '$order_id', '$voterNumber', '$voterName', '$state', $amount, 'Pending', NOW()
                )";
                
                $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                
                if($insertSuccess) {
                    // WhatsApp to admin
                    $whamessage = "Dear Admin,\nNew Voter PDF Request\n\nOrder ID: *$order_id*\nVoter No: *$voterNumber*\nName: $voterName\nState: $state";
                    @send_sms_credentials($webdata['phone'], $whamessage);
                    
                    // WhatsApp to User
                    $whamessage = "Dear {$udata['name']},\nYour Voter PDF request submitted.\n\n*Order ID*: {$order_id}\n*Voter No*: {$voterNumber}\n\n⏱️ Wait 30 minutes";
                    @send_sms($udata['phone'], $whamessage);
                    
                    $show_popup = true;
                    $popup_order_id = $order_id;
                    $popup_voter_number = $voterNumber;
                    
                } else {
                    mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                    echo '<script>Swal.fire("Error", "Failed to save. Balance restored.", "error");</script>';
                }
            } else {
                echo '<script>Swal.fire("Error", "Balance update failed!", "error");</script>';
            }
        } else {
            echo '<script>Swal.fire("Insufficient Balance", "Need: ₹' . $amount . '", "error");</script>';
        }
    } else {
        echo '<script>Swal.fire("Error", "Please fill all fields!", "error");</script>';
    }
}

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

<?php if($show_popup): ?>
<div id="submissionPopup" class="popup-overlay" style="display:flex;">
    <div class="popup-container">
        <div class="success-icon">✅</div>
        <h3>REQUEST SUBMITTED!</h3>
        
        <div class="order-details">
            <p><strong>🗳️ Voter PDF Request</strong></p>
            <div class="detail-box">
                <label>📝 Order ID:</label>
                <span><?=$popup_order_id?></span>
            </div>
            <div class="detail-box">
                <label>🗳️ Voter Number:</label>
                <span><?=$popup_voter_number?></span>
            </div>
        </div>
        
        <div class="processing-info">
            <h4>⏱️ PROCESSING TIME: 30 minutes</h4>
        </div>
        
        <button onclick="window.location='voter_pdf_list.php'" class="btn-ok">OK, Got It!</button>
    </div>
</div>

<script>
setTimeout(function() { window.location.href = 'voter_pdf_list.php'; }, 5000);
</script>
<?php endif; ?>

<style>
.popup-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.popup-container {
    background: white;
    border-radius: 15px;
    padding: 30px;
    max-width: 450px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
.success-icon {
    font-size: 60px;
    text-align: center;
    margin-bottom: 15px;
}
.detail-box {
    background: white;
    padding: 10px;
    margin: 10px 0;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
}
.btn-ok {
    width: 100%;
    background: #4CAF50;
    color: white;
    border: none;
    padding: 12px;
    border-radius: 8px;
    cursor: pointer;
    margin-top: 15px;
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-md-4 mb-2">
                <div class="card">
                    <div class="card-header bg-primary text-white py-2">
                        <div class="d-flex align-items-center">
                            <span>🗳️ Voter PDF Download</span>
                            <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
                        </div>
                    </div>
                    <div class="p-3">
                        <form action="" method="POST">
                            <div class="mb-3">
                                <label><b>Voter Number</b></label>
                                <input type="text" name="voterNumber" placeholder="Enter Voter Number" maxlength="45" 
                                       oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" 
                                       class="form-control" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Name (As on Voter Card)</b></label>
                                <input type="text" name="voterName" placeholder="Enter Full Name" class="form-control" required>
                            </div>
                            
                            <div class="mb-3">
                                <label><b>Select State</b></label>
                                <select class="form-control" name="state" id="stateSelect" onchange="toggleOtherState()" required>
                                    <option value="">-- Select State --</option>
                                    <option>Andhra Pradesh</option>
                                    <option>Arunachal Pradesh</option>
                                    <option>Assam</option>
                                    <option>Bihar</option>
                                    <option>Chhattisgarh</option>
                                    <option>Goa</option>
                                    <option>Gujarat</option>
                                    <option>Haryana</option>
                                    <option>Himachal Pradesh</option>
                                    <option>Jharkhand</option>
                                    <option>Karnataka</option>
                                    <option>Kerala</option>
                                    <option>Madhya Pradesh</option>
                                    <option>Maharashtra</option>
                                    <option>Manipur</option>
                                    <option>Meghalaya</option>
                                    <option>Mizoram</option>
                                    <option>Nagaland</option>
                                    <option>Odisha</option>
                                    <option>Punjab</option>
                                    <option>Rajasthan</option>
                                    <option>Sikkim</option>
                                    <option>Tamil Nadu</option>
                                    <option>Telangana</option>
                                    <option>Tripura</option>
                                    <option>Uttar Pradesh</option>
                                    <option>Uttarakhand</option>
                                    <option>West Bengal</option>
                                    <option>Delhi</option>
                                    <option>Other State</option>
                                </select>
                            </div>
                            
                            <div class="mb-3" id="otherStateDiv" style="display:none">
                                <label><b>Enter Your State Name</b></label>
                                <input type="text" name="otherState" id="otherStateInput" placeholder="Type state name" class="form-control">
                            </div>
                            
                            <div class="d-flex justify-content-between mb-3">
                                <button type="button" class="btn btn-secondary">₹<?php echo number_format($udata['voter_direct_pdf_fee'] ?? 40, 2); ?></button>
                                <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">
                                    <i class="fas fa-paper-plane"></i> Submit
                                </button>
                                <a href="voter_pdf_list.php" class="btn btn-warning"><i class="fas fa-list"></i> My Requests</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8 mb-2">
                <div class="card">
                    <div class="card-header bg-primary text-white py-2">
                        <span>📋 Important Information</span>
                    </div>
                    <div class="p-3">
                        <div class="alert alert-info">
                            <h5><i class="fas fa-info-circle"></i> Service Details</h5>
                            <ul>
                                <li><b>Service:</b> Voter PDF Original Download</li>
                                <li><b>Amount:</b> ₹<?php echo number_format($udata['voter_direct_pdf_fee'] ?? 40, 2); ?></li>
                                <li><b>Processing Time:</b> 30 minutes</li>
                                <li><b>Delivery:</b> Instant PDF download</li>
                            </ul>
                        </div>
                        
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-exclamation-triangle"></i> Important Notes</h5>
                            <ul>
                                <li>No OTP required</li>
                                <li>Original PDF मिलेगी</li>
                                <li>30 मिनट wait करें</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleOtherState() {
    var stateSelect = document.getElementById('stateSelect');
    var otherStateDiv = document.getElementById('otherStateDiv');
    var otherStateInput = document.getElementById('otherStateInput');
    
    if (stateSelect.value === 'Other State') {
        otherStateDiv.style.display = 'block';
        otherStateInput.required = true;
    } else {
        otherStateDiv.style.display = 'none';
        otherStateInput.required = false;
    }
}
</script>

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