<?php 
include 'header.php';

$msg = "";
$err = "";

// Function to generate card number
function generateCardNumber() {
    $card = '';
    for($i = 0; $i < 16; $i++) {
        $card .= rand(0, 9);
        if(($i + 1) % 4 == 0 && $i != 15) {
            $card .= ' '; // Add space for readability
        }
    }
    return $card;
}

// Handle card approval
if (isset($_post['app'])) {
    $tid = mysqli_real_escape_string($link, $_GET['app']);
    
    // Start transaction
    mysqli_begin_transaction($link);
    
    try {
        // Get card purchase details
        $purchaseQuery = mysqli_query($link, "SELECT * FROM card_purchases WHERE id = '$tid'");
        if(mysqli_num_rows($purchaseQuery) == 0) {
            throw new Exception("Card purchase not found");
        }
        
        $purchase = mysqli_fetch_assoc($purchaseQuery);
        $userId = $purchase['user_id'];
        $email = $purchase['email'];
        
        // Generate card details
        $card_number = generateCardNumber();
        $cvc = rand(100, 999);
        $expiry_date = date('m/y', strtotime('+4 years'));
        
        // Update card_purchases table
        $update_query = "UPDATE card_purchases SET 
                        status = 'Approved',
                        card_number = '$card_number',
                        cvc = '$cvc',
                        expiry_date = '$expiry_date',
                        approved_date = NOW()
                        WHERE id = '$tid'";
        
        $result = mysqli_query($link, $update_query);
        
        if(!$result) {
            throw new Exception("Card approval failed: " . mysqli_error($link));
        }
        
        // Update user table with card details
        $update_user = "UPDATE users SET 
                       card_number = '$card_number',
                       card_cvc = '$cvc',
                       card_expiry = '$expiry_date',
                       link_card = 'Approved'
                       WHERE id = '$userId'";
        
        $user_result = mysqli_query($link, $update_user);
        
        if(!$user_result) {
            throw new Exception("User update failed: " . mysqli_error($link));
        }
        
        // Get user details for email
        $userQuery = mysqli_query($link, "SELECT * FROM users WHERE id = '$userId'");
        $user = mysqli_fetch_assoc($userQuery);
        $username = $user['fname'];
        $email = $user['email'];

        // Send card approval email
        $subject = "Your Card Application Has Been Approved!";
        $body = "
        <div style='background: #E4E9F0; padding: 20px; font-family: Arial, sans-serif;'>
            <div style='max-width: 600px; margin: 0 auto; background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);'>
                <!-- Header -->
                <div style='background-color: #1e293b; padding: 16px; display: flex; align-items: center;'>
                    <div style='display: flex; align-items: center;'>
                        <center><img src='$siteurl/app/image/logo.png' width='100px' style='margin-right: 8px;'></center>
                    </div>
                </div>

                <!-- Main Content -->
                <div style='padding: 32px; text-align: center;'>
                    <h1 style='font-size: 28px; color: #1e293b; margin-bottom: 24px; line-height: 1.2;'>
                        Congratulations! Your Card Is Approved
                    </h1>

                    <p style='font-size: 18px; color: #4b5563; margin-bottom: 32px;'>
                        Dear <b>$username</b>, we're delighted to inform you that your application for the $sitename Card has been approved!
                    </p>

                    <div style='background: #f8fafc; border-radius: 8px; padding: 16px; margin-bottom: 24px; text-align: center;'>
                        <p style='margin-bottom: 8px;'>Status: <span style='color: #16a34a; font-weight: bold;'>ACTIVE</span></p>
                        <p style='margin-bottom: 8px;'>Card Number: $card_number</p>
                        <p style='margin-bottom: 8px;'>Expiry Date: $expiry_date</p>
                        <p style='margin-bottom: 8px;'>Approval Date: ".date('F j, Y')."</p>
                    </div>

                    <!-- Support Section -->
                    <div style='margin-top: 32px; border-top: 1px solid #e5e7eb; padding-top: 24px; text-align: left;'>
                        <p style='color: #4b5563; margin-bottom: 8px;'><strong>Need help with your new card?</strong></p>
                        <p style='color: #4b5563; margin-bottom: 8px;'>Contact Card Services at $sitemail or call (800) 555-1234</p>
                        <p style='color: #4b5563; font-weight: bold; margin-bottom: 0;'>The $sitename Card Team</p>
                    </div>

                    <!-- Footnotes -->
                    <div style='margin-top: 32px; font-size: 12px; color: #6b7280; text-align: left;'>
                        <p style='margin-bottom: 4px;'>This is a confidential communication regarding your $sitename account.</p>
                        <p style='margin-bottom: 4px;'>If you didn't apply for this card, please contact us immediately.</p>
                    </div>
                </div>
            </div>
        </div>";

        $send = sendMail($email, $subject, $body);
        
        // Commit transaction if everything succeeded
        mysqli_commit($link);
        
        if ($send) {
            $_SESSION['success'] = "Card approved and email sent successfully!";
        } else {
            $_SESSION['warning'] = "Card approved but email could not be sent";
        }
        
         echo "<script>
    window.location.href = 'card.php';
</script>";
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction if any error occurs
        mysqli_rollback($link);
        $_SESSION['error'] = $e->getMessage();
        echo "<script>
    window.location.href = 'card.php';
</script>";
        exit();
    }
}

// Handle card deletion
if (isset($_GET['del'])) {
    $tid = mysqli_real_escape_string($link, $_GET['del']);
    $del = mysqli_query($link, "DELETE FROM card_purchases WHERE id = '$tid'");
    if ($del) {
        $_SESSION['success'] = "Card request deleted successfully";
    } else {
        $_SESSION['error'] = "Error deleting card request: " . mysqli_error($link);
    }
    echo "<script>
    window.location.href = 'card.php';
</script>";

    exit();
}
?>




<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
  
  

  <link rel="stylesheet" href=" https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href=" https://cdn.datatables.net/1.10.19/css/dataTables.jqueryui.min.css">
  <link rel="stylesheet" href=" https://cdn.datatables.net/buttons/1.5.6/css/buttons.jqueryui.min.css">



  

  <link rel="stylesheet" href=" https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
  <link rel="stylesheet" href=" https://cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap.min.css">
  <link rel="stylesheet" href="">
 
  

  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
 

  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/dataTables.jqueryui.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>

  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.jqueryui.min.js"></script>
   
  <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
  <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>
<style>
.table-responsive {
overflow-x: hidden;
}
@media (max-width: 8000px) {
.table-responsive {
overflow-x: auto;
}
</style>
<div class="page-content">
    <div class="container-fluid">
<?php 
    if ($msg != "") {
        echo "<div style='padding:20px;background-color:#dce8f7;color:black'> $msg</div class='btn btn-success'>" ."</br></br>"; 
    }
    if ($err != "") {
        echo customAlert("error", $err);
    }

 ?>
			<div class="row">
			    <div class="col-lg-12">
			        <div class="card">
			            <div class="card-header">
			                <h4 class="card-title mb-0">All Pending Card Request</h4>
			            </div><!-- end card header -->

			            <div class="card-body">
			                <div id="customerList">
			                    

			                    <div class="table-responsive table-card mt-3 mb-1">
			                    	<table id="myTable" class="table-responsive" >  
								        <thead class="table-light">
			                                <tr class="info">
			                                    
												<th>Name</th>
												<th>Email</th>
												<th>Amount</th>
												<th>Bill Address</th>
												<th>Proofs</th>
												<th>Status</th>
												<th>Date</th>
						                        <th>Action</th>						                        
						                        <th>Action</th>
								
											</tr>
			                            </thead>
								        <tbody>
									<?php 
									$sql= "SELECT * FROM card_purchases  WHERE status = 'pending' ORDER BY id DESC ";
									  $result = mysqli_query($link,$sql);
									  if(mysqli_num_rows($result) > 0){
										  while($row = mysqli_fetch_assoc($result)){   
										  	$userId = $row['user_id'];
										  	$user = mysqli_query($link, "SELECT * FROM users WHERE id = '$userId' ");
											$user_r = mysqli_fetch_assoc($user);
				  						?>
				  		
						<tr class="primary">
						<form method="post">
                            <input type="hidden" name="name" value="<?php echo $user_r['fname'] ?>">
							<input type="hidden" name="email" value="<?php echo $user_r['email'] ?>">
                        	<input type="hidden" name="deposit_id" value="<?php echo $row['id'] ?>">
                        	<input type="hidden" name="status" value="<?php echo $row['status'] ?>">
                        	<input type="hidden" name="amount" value="<?php echo $row['amount'] ?>">
                        	<input type="hidden" name="method" value="<?php echo $row['coin'] ?>">
                        	<input type="hidden" name="deposit_to" value="<?php echo $row['deposit_to'] ?>">
                        	<input type="hidden" name="userId" value="<?php echo $row['userid'] ?>">
							<td><?php echo $user_r['username'] ?></td>
							<td><?php echo $user_r['email'] ?></td>
							<td><?php echo $row['amount'] ?></td>
							<td><?php echo $row['address'] ?></td>
							<td> <img width='100' src='<?php echo $row['proof_path'] ?>'> </td>

							<td><?php echo $row['status'] ?></td>
							<td><?php echo $row['purchase_date'] ?></td>
							
                            <td>
                            
                            <a onclick="return confirm('Carry out action')" href="?app=<?php echo $row['id']; ?>" class="btn btn-success">Approve</a>
                            </td>

							<td><a href="?del=<?php echo $row['id']; ?>" class="btn btn-danger">Delete</a></td>
							
   
						</form>
						</tr>
						
					  <?php
 }
			  }
			  ?>
					</tbody>

								      </table>  

			                        
			                    </div>


			                </div>
			            </div><!-- end card -->
			        </div>
			        <!-- end col -->
			    </div>
			    <!-- end col -->
			</div>
			<!-- end row -->


	</div>
</div>
<script>
$(document).ready(function(){
    $('#myTable').dataTable();
});
</script>

<?php include 'footer.php'; ?>