<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/tngweb/header.php');

$userPhone = $udata['phone'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['check_status']) && !empty($_POST['record_id'])) {
    $recordId = intval($_POST['record_id']);
    $user = $udata['phone'];

   
    $query = mysqli_query($tng_conn, "SELECT * FROM voter_mobile_link_requests WHERE id = $recordId AND username = '$user' AND status = 'Pending'");
    if (mysqli_num_rows($query) == 0) {
        echo "<script>Swal.fire('Error','Record not found or already processed','error').then(()=>window.location='voter_mobile_link_manual_history.php');</script>";
        exit;
    }
    $record = mysqli_fetch_assoc($query);
    $appNo = $record['application_no'];
    $fee = (float) $record['fee'];

  
    $res = voter_mobile_link_manual_status_api_run($appNo);
    $newStatus = $res['status'] ?? 'Pending';
    $newMessage = $res['message'] ?? $res['error'] ?? '';

   
    mysqli_begin_transaction($tng_conn);
    try {
        
        $stmt = $tng_conn->prepare("UPDATE voter_mobile_link_requests SET status = ?, error_message = ? WHERE id = ?");
        $stmt->bind_param("ssi", $newStatus, $newMessage, $recordId);
        $stmt->execute();

        if ($newStatus === 'Refunded') {
          
            $balQuery = mysqli_query($tng_conn, "SELECT balance FROM users WHERE phone = '$user'");
            $balRow = mysqli_fetch_assoc($balQuery);
            $currentBalance = (float) $balRow['balance'];
            $newBalance = $currentBalance + $fee;

            $refundStmt = $tng_conn->prepare("UPDATE users SET balance = ? WHERE phone = ?");
            $refundStmt->bind_param("ds", $newBalance, $user);
            $refundStmt->execute();

            $purpose = "Refund - Voter Mobile Link Manual (App: $appNo)";
            $historyStmt = $tng_conn->prepare("INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) VALUES (?, ?, ?, ?, '1', 'Credit')");
            $historyStmt->bind_param("sds", $user, $fee, $newBalance, $purpose);
            $historyStmt->execute();
        }

        mysqli_commit($tng_conn);

      
        if ($newStatus === 'Success') {
            echo "<script>Swal.fire({icon:'success', title:'Status Updated', text:'Mobile linked successfully!', timer:2500}).then(()=>window.location='voter_mobile_link_manual_history.php');</script>";
        } elseif ($newStatus === 'Refunded') {
            echo "<script>Swal.fire({icon:'success', title:'Refunded', text:'₹$fee has been credited back to your wallet.', timer:3000}).then(()=>window.location='voter_mobile_link_manual_history.php');</script>";
        } else {
            echo "<script>Swal.fire({icon:'info', title:'Still Pending', text:'Please check again later.', timer:2500}).then(()=>window.location='voter_mobile_link_manual_history.php');</script>";
        }
    } catch (Exception $e) {
        mysqli_rollback($tng_conn);
        echo "<script>Swal.fire('Error','Database error: ".addslashes($e->getMessage())."','error').then(()=>window.location='voter_mobile_link_manual_history.php');</script>";
    }
    exit;
}

$historyQuery = mysqli_query($tng_conn, "SELECT * FROM voter_mobile_link_requests WHERE username = '".mysqli_real_escape_string($tng_conn, $userPhone)."' ORDER BY date DESC");
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">

<div class="page-wrapper">
<div class="page-content">
<div class="card shadow-lg border-0">
<div class="card-body">
<div class="d-flex justify-content-between align-items-center mb-4">
  <a href="voter_mobile_link_manual.php" class="btn btn-primary rounded-pill px-4"><i class="fa fa-plus me-2"></i> New Request</a>
  <h4 class="fw-bold text-primary mb-0">🗳️ Voter Mobile Link History (Manual)</h4>
</div>
<div class="table-responsive">
<table id="historyTable" class="table table-hover align-middle text-center w-100">
<thead class="bg-dark text-white">
<tr><th>#</th><th>Date & Time</th><th>Application No.</th><th>EPIC</th><th>Mobile</th><th>Full Name</th><th>State</th><th>Fee</th><th>Status</th><th>Action</th></tr>
</thead>
<tbody>
<?php 
$count = 0;
while ($row = mysqli_fetch_assoc($historyQuery)):
$count++;
$statusText = $row['status'];
$feeAmount = number_format($row['fee'], 2);

// match remove karke ye use karo
switch ($statusText) {
    case 'Pending':
        $badge = 'warning';
        break;
    case 'Success':
        $badge = 'success';
        break;
    case 'Refunded':
        $badge = 'danger';
        break;
    default:
        $badge = 'secondary';
}
?>
<tr>
<td><?= $count ?></td>
<td><?= date('d-m-Y h:i A', strtotime($row['date'])) ?></td>
<td><?= htmlspecialchars($row['application_no']) ?></td>
<td><?= htmlspecialchars($row['epic_number']) ?></td>
<td><?= htmlspecialchars($row['mob_number']) ?></td>
<td><?= htmlspecialchars($row['fullname']) ?></td>
<td><?= htmlspecialchars($row['state']) ?></td>
<td>₹ <?= $feeAmount ?></td>
<td><span class="badge bg-<?= $badge ?> px-3 py-2 rounded-pill"><?= $statusText ?></span></td>
<td>
<?php if ($statusText == 'Pending'): ?>
<form method="post" style="display:inline;">
  <input type="hidden" name="record_id" value="<?= $row['id'] ?>">
  <button type="submit" name="check_status" class="btn btn-sm btn-warning rounded-pill px-3">🔄 Check Status</button>
</form>
<?php else: ?>
<span class="text-muted">—</span>
<?php endif; ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script>
$(document).ready(function(){
    $('#historyTable').DataTable({
        responsive: true,
        pageLength: 10,
        order: [[1, 'desc']],
        dom: "<'row mb-3'<'col-md-6'l><'col-md-6 text-end'B>>" +
             "<'row'<'col-12'tr>>" +
             "<'row mt-3'<'col-md-5'i><'col-md-7'p>>",
        buttons: [
            { extend: 'excel', className: 'btn btn-success btn-sm rounded-pill px-3' },
            { extend: 'pdf', className: 'btn btn-danger btn-sm rounded-pill px-3' },
            { extend: 'print', className: 'btn btn-primary btn-sm rounded-pill px-3' }
        ],
        columnDefs: [{ orderable: false, targets: 0 }]
    }).on('order.dt search.dt', function(){
        this.column(0, {search:'applied', order:'applied'}).nodes().each(function(cell,i){
            cell.innerHTML = i+1;
        });
    }).draw();
});
</script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<?php include('../template/tngweb/footer.php'); ?>