<?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_Mobile_Link_Service'] != "YES") {
    echo '<script>
        Swal.fire("Access Denied", "Voter Mobile Link service not active!", "info");
        setTimeout(function(){ window.location="index.php"; }, 2000);
    </script>';
    exit;
}

$show_popup = false;
$popup_order_id = '';
$popup_epic = '';
$popup_mobile = '';

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

    if (!empty($voterEpicNumber) && !empty($mobileNumber) && !empty($state)) {
        
        if (!preg_match('/^[0-9]{10}$/', $mobileNumber)) {
            echo '<script>Swal.fire("Error", "Enter valid 10-digit mobile number!", "error");</script>';
        } else {
            $amount = floatval($udata['voter_mobile_link_fee'] ?? 80);
            $old_balance = $udata['balance'];
            $new_balance = $old_balance - $amount;

            if ($udata['balance'] >= $amount) {
                
                // Check duplicate
                $existingRequest = mysqli_query($ahk_conn, "SELECT id FROM voter_mobile_link_requests 
                    WHERE voter_epic_number='$voterEpicNumber' AND status IN ('Pending','Processing') 
                    AND username='{$udata['name']}'");
                
                if(mysqli_num_rows($existingRequest) > 0) {
                    echo '<script>Swal.fire("Duplicate", "This EPIC already has a pending request!", "warning");</script>';
                } else {
                    $order_id = 'VML' . time() . rand(1000, 9999);
                    
                    $updateSuccess = mysqli_query($ahk_conn, "UPDATE users SET balance = $new_balance WHERE phone = '{$udata['phone']}'");
                    
                    if ($updateSuccess) {
                        // Insert transaction
                        $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 Mobile Link', 'Debit', '$voterEpicNumber', 'Voter Mobile Link',
                            $amount, $amount, $old_balance, $new_balance, '$order_id', '$voterEpicNumber',
                            'Rs.$amount debited for Voter Mobile Link', NOW(), 'Success'
                        )";
                        mysqli_query($ahk_conn, $reportSql);
                        
                        // Insert request
                        $requestSql = "INSERT INTO voter_mobile_link_requests (
                            user_id, username, name, mobile, order_id, voter_epic_number, voter_name, 
                            mobile_number, state, amount, status, request_date
                        ) VALUES (
                            '{$udata['phone']}', '{$udata['name']}', '{$udata['name']}', '{$udata['phone']}',
                            '$order_id', '$voterEpicNumber', '', '$mobileNumber', '$state', $amount, 'Pending', NOW()
                        )";
                        
                        $insertSuccess = mysqli_query($ahk_conn, $requestSql);
                        
                        if($insertSuccess) {
                            // WhatsApp
                            $whamessage = "Dear Admin,\nNew Voter Mobile Link Request!\n\nOrder ID: *{$order_id}*\nEPIC: *{$voterEpicNumber}*\nMobile: *{$mobileNumber}*\nState: {$state}";
                            @send_sms($webdata['phone'], $whamessage);
                            
                            $whamessage = "Dear {$udata['name']},\n\nVoter Mobile Link Request Submitted!\n\n*Order ID:* {$order_id}\n*EPIC:* {$voterEpicNumber}\n*Mobile:* {$mobileNumber}\n\nProcessing: 1-5 hours";
                            @send_sms($udata['phone'], $whamessage);
                            
                            $show_popup = true;
                            $popup_order_id = $order_id;
                            $popup_epic = $voterEpicNumber;
                            $popup_mobile = $mobileNumber;
                        } else {
                            mysqli_query($ahk_conn, "UPDATE users SET balance = $old_balance WHERE phone = '{$udata['phone']}'");
                            echo '<script>Swal.fire("Error", "Failed. Balance restored.", "error");</script>';
                        }
                    } else {
                        echo '<script>Swal.fire("Error", "Balance update failed!", "error");</script>';
                    }
                }
            } else {
                echo '<script>Swal.fire("Insufficient Balance", "", "error");</script>';
            }
        }
    } else {
        echo '<script>Swal.fire("Error", "Please fill all fields!", "error");</script>';
    }
}

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

<?php if($show_popup): ?>
<div class="popup-overlay" id="successPopup" style="display:flex;">
    <div class="popup-box">
        <div class="success-icon">✅</div>
        <h3>Request Submitted Successfully!</h3>
        
        <div style="background:#f5f5f5;padding:15px;border-radius:10px;margin:20px 0;">
            <p><strong>Order ID:</strong> <?php echo $popup_order_id; ?></p>
            <p><strong>EPIC Number:</strong> <?php echo $popup_epic; ?></p>
            <p><strong>Mobile Number:</strong> <?php echo $popup_mobile; ?></p>
        </div>
        
        <div style="background:linear-gradient(135deg,#d4edda,#c3e6cb);padding:15px;border-radius:10px;text-align:center;">
            <h4>⏰ Processing Time: 1-5 Hours</h4>
        </div>
        
        <button onclick="window.location='voter_mobile_list.php'" style="width:100%;background:#27ae60;color:white;border:none;padding:12px;border-radius:8px;margin-top:10px;cursor:pointer;">
            OK, Got It!
        </button>
    </div>
</div>
<script>
setTimeout(function(){ window.location='voter_mobile_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.7);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.popup-box {
    background: #fff;
    border-radius: 15px;
    padding: 25px;
    max-width: 400px;
    width: 90%;
    box-shadow: 0 10px 40px rgba(0,0,0,0.3);
}
.success-icon {
    font-size: 60px;
    text-align: center;
    margin-bottom: 10px;
}
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="row">
            <div class="col-lg-4 col-md-5 mb-3">
                <div class="card">
                    <div class="card-header bg-success text-white py-2">
                        <span><i class="fas fa-mobile-alt"></i> Voter Mobile Link</span>
                        <button class="btn btn-sm btn-dark float-right" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
                    </div>
                    <div class="card-body">
                        <div class="text-center mb-3">
                            <span style="background:linear-gradient(135deg,#28a745,#20c997);color:#fff;padding:8px 15px;border-radius:20px;font-size:12px;font-weight:600;">
                                <i class="fas fa-bolt"></i> NO OTP REQUIRED
                            </span>
                        </div>
                        
                        <form method="POST">
                            <div class="form-group">
                                <label><b>Voter EPIC Number <span class="text-danger">*</span></b></label>
                                <input type="text" name="voterEpicNumber" class="form-control" placeholder="ABC1234567" 
                                       maxlength="20" oninput="this.value=this.value.toUpperCase().replace(/\s/g,'')" required>
                                <small class="text-muted">Voter Card पर लिखा EPIC Number</small>
                            </div>
                            
                            <div class="form-group">
                                <label><b>Mobile Number (Link करना है) <span class="text-danger">*</span></b></label>
                                <input type="text" name="mobileNumber" class="form-control" placeholder="10 digit" 
                                       maxlength="10" oninput="this.value=this.value.replace(/[^0-9]/g,'')" required>
                                <small class="text-muted">यह Number Voter Card से Link होगा</small>
                            </div>
                            
                            <div class="form-group">
                                <label><b>State <span class="text-danger">*</span></b></label>
                                <select name="state" id="stateSelect" class="form-control" onchange="toggleOther()" required>
                                    <option value="">-- Select State --</option>
                                    <option>Andhra Pradesh</option>
                                    <option>Arunachal Pradesh</option>
                                    <option>Assam</option>
                                    <option>Bihar</option>
                                    <option>Chhattisgarh</option>
                                    <option>Delhi</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>Jammu and Kashmir</option>
                                    <option>Ladakh</option>
                                    <option value="Other State">Other State</option>
                                </select>
                            </div>
                            
                            <div class="form-group" id="otherDiv" style="display:none;">
                                <input type="text" name="otherState" class="form-control" placeholder="Enter State Name">
                            </div>
                            
                            <div class="row mb-3">
                                <div class="col-6">
                                    <div class="alert alert-success py-2 mb-0 text-center">
                                        <small>Balance</small><br><b>₹<?php echo number_format($udata['balance'], 2); ?></b>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="alert alert-warning py-2 mb-0 text-center">
                                        <small>Charge</small><br><b>₹<?php echo number_format($udata['voter_mobile_link_fee'] ?? 80, 2); ?></b>
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" name="submit" class="btn btn-success btn-block" onclick="return confirm('Submit करना चाहते हैं?')">
                                <i class="fas fa-paper-plane"></i> Submit Request
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-8 col-md-7 mb-3">
                <div class="card">
                    <div class="card-header bg-success text-white py-2">
                        <span>ℹ️ Service Information</span>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <h6 style="color:#155724;"><i class="fas fa-info-circle"></i> Service Details</h6>
                            <ul style="font-size:13px;color:#155724;">
                                <li><b>Processing Time:</b> 1-5 Hours</li>
                                <li><b>No OTP Required</b></li>
                                <li>Mobile Number Voter Card से Link हो जाएगा</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function toggleOther() {
    var sel = document.getElementById('stateSelect');
    document.getElementById('otherDiv').style.display = (sel.value === 'Other State') ? 'block' : 'none';
}
</script>

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