<?php
session_start();
require_once __DIR__ . '/includes/config.php';

// Admin authentication check
if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php"); 
    exit;
}

$alertMessage = '';
$alertType = '';

// ==========================================
// Form Submit Hone Par Gateway Logic
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_payout'])) {
    
    // Form Inputs
    $amount         = round((float)$_POST['amount'], 2);
    $account_name   = trim($_POST['account_name']);
    $account_number = trim($_POST['account_number']);
    $ifsc_code      = trim($_POST['ifsc_code']);
    $bank_name      = trim($_POST['bank_name']);
    $order_no       = trim($_POST['order_no']);

    // LPPAY (Pay-X) API Credentials
    $merchant_id = 248; 
    $secret_key  = "992b35f2c59b060774552692d5453dc1"; 
    $api_url     = "https://api.rdonepay.com/api/pay/create/order"; 
    
    // Website ka domain (Webhook ke liye)
    $domain = "https://" . $_SERVER['HTTP_HOST'];
    $notify_url = $domain . "/webhook-donepay"; // Laravel webhook

    // API Payload
    $data = [
        'type'            => 1, // 1 = Withdraw / Payout
        'merchantId'      => (int)$merchant_id,
        'merchantOrderNo' => $order_no,
        'orderAmount'     => $amount,
        'accountName'     => $account_name,
        'cardNumber'      => $account_number,
        'ifsc'            => $ifsc_code,
        'bankName'        => $bank_name,
        'notifyUrl'       => $notify_url,
        'phone'           => '9999999999',
        'email'           => 'admin@cosco.com',
    ];

    // --- Signature Builder (MD5) ---
    ksort($data); 
    $sign_params = [];
    foreach ($data as $key => $val) {
        if ($val !== null && $val !== '') {
            $sign_params[] = $key . "=" . $val;
        }
    }
    $sign_params[] = "secret=" . $secret_key;
    $data['sign'] = md5(implode("&", $sign_params));

    // --- cURL Request to Gateway ---
    $ch = curl_init($api_url);
    $payload = json_encode($data);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    
    // 🔥 YAHAN AAPKA IP BINDING HAI 🔥
    curl_setopt($ch, CURLOPT_INTERFACE, '187.127.128.155'); 
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json',
        'User-Agent: Mozilla/5.0'
    ]);

    $response = curl_exec($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        $alertMessage = "CURL Error: " . $curl_error;
        $alertType = "danger";
    } else {
        $res_data = json_decode($response, true);

        // API Success Check
        if (isset($res_data['code']) && $res_data['code'] == 200) {
            $platformOrderNo = $res_data['data']['orderNo'] ?? 'Unknown';
            $alertMessage = "✅ Payout Successfully Sent! Gateway Order ID: " . $platformOrderNo;
            $alertType = "success";

            // 🔥 DATABASE ME SAVE KARO HISTORY KE LIYE 🔥
            if (isset($conn)) {
                $status = "Processing";
                $stmt = $conn->prepare("INSERT INTO manual_payouts (order_no, amount, account_name, account_number, ifsc_code, bank_name, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
                if ($stmt) {
                    $stmt->bind_param("sdsssss", $order_no, $amount, $account_name, $account_number, $ifsc_code, $bank_name, $status);
                    $stmt->execute();
                    $stmt->close();
                }
            }
        } else {
            // API Rejected
            $error_msg = $res_data['message'] ?? "Unknown API Error";
            $alertMessage = "❌ Gateway Rejected: " . $error_msg;
            $alertType = "danger";
        }
    }
}

// Generate New Unique Order ID for the form
$autoOrderId = "PAYOUT" . time() . rand(100, 999);

// Fetch History from Database
$historyList = [];
if (isset($conn)) {
    // try to fetch records, suppress error if table doesn't exist yet
    $res = @$conn->query("SELECT * FROM manual_payouts ORDER BY id DESC LIMIT 50");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $historyList[] = $row;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manual Withdraw - Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
  /* ================= SAME THEME AS DASHBOARD ================= */
  :root { 
    --bg: #f3f4f6; --sidebar: #111827; --card: #ffffff; 
    --text-main: #1f2937; --text-muted: #6b7280; --border: #e5e7eb; 
    --accent: #374151; 
  }
  * { box-sizing: border-box; } 
  body { 
    margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif; 
    background: var(--bg); color: var(--text-main); min-height: 100vh; display: flex; 
  }
  .svg-icon { width: 18px; height: 18px; vertical-align: middle; margin-right: 8px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
  
  /* SIDEBAR */
  .sidebar { width: 250px; background: var(--sidebar); color: #fff; height: 100vh; position: fixed; left: 0; top: 0; padding: 20px; overflow-y: auto; }
  .logo { font-weight: 700; color: #fff; margin-bottom: 30px; display: flex; align-items: center; font-size: 18px; letter-spacing: 0.5px; }
  .nav a { display: flex; align-items: center; padding: 12px 14px; border-radius: 6px; text-decoration: none; color: #9ca3af; margin-bottom: 5px; font-weight: 500; font-size: 15px; transition: background 0.2s, color 0.2s; }
  .nav a:hover, .nav a.active { background: var(--accent); color: #ffffff; }
  
  /* MAIN CONTENT */
  .main { margin-left: 250px; padding: 30px; flex: 1; }
  .topbar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 25px; }
  .title { font-size: 22px; font-weight: 700; color: var(--text-main); }
  
  /* FORM PANEL */
  .panel { background: var(--card); border-radius: 8px; border: 1px solid var(--border); padding: 30px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); max-width: 800px; margin: 0 auto; margin-bottom: 30px; }
  .panel h3 { margin-top: 0; padding-bottom: 15px; border-bottom: 1px solid var(--border); font-size: 18px; }
  .form-group { margin-bottom: 20px; }
  .form-group label { display: block; font-weight: 600; margin-bottom: 8px; color: var(--text-main); font-size: 14px; }
  .form-control { width: 100%; padding: 12px 15px; border: 1px solid var(--border); border-radius: 6px; font-size: 15px; background: #f9fafb; transition: border 0.3s; }
  .form-control:focus { border-color: var(--text-muted); outline: none; background: #fff; }
  .form-control[readonly] { background: #e5e7eb; cursor: not-allowed; }
  
  .row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
  @media(max-width: 768px) { .row { grid-template-columns: 1fr; } }

  .btn { width: 100%; padding: 14px; background: #10b981; color: #fff; border: none; border-radius: 6px; font-size: 16px; font-weight: 600; cursor: pointer; transition: background 0.3s; margin-top: 10px; }
  .btn:hover { background: #059669; }

  /* ALERTS */
  .alert { padding: 15px; border-radius: 6px; margin-bottom: 20px; font-weight: 500; font-size: 15px; }
  .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0; }
  .alert-danger { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }

  /* TABLE STYLES */
  .table-responsive { overflow-x: auto; }
  .table { width: 100%; border-collapse: collapse; margin-top: 10px; }
  .table th, .table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 14px; }
  .table th { background-color: #f9fafb; color: var(--text-muted); font-weight: 600; text-transform: uppercase; font-size: 12px; }
  .table tbody tr:hover { background-color: #f9fafb; }
  .badge { padding: 5px 10px; border-radius: 50px; font-size: 12px; font-weight: 600; }
  .badge-warning { background: #fef3c7; color: #92400e; }
</style>
</head>
<body>

<div class="sidebar">
  <div class="logo">
      <svg class="svg-icon" viewBox="0 0 24 24"><path d="M13 2L3 14h9l-1 8 10-12h-9l1-8z"></path></svg>
      COSCO ADMIN
  </div>
  <nav class="nav">
    <a href="dashboard.php">Dashboard</a> 
    <a href="users.php">Users</a>
    <a href="deposits.php">Deposits</a>
    <a href="withdraw.php">Withdrawals</a>
    <a href="products.php">Products</a>
    <a href="daily_income.php">Daily Income</a>
    <a href="notice.php">Notices</a>
    <a href="reports.php">Backup Dashboard</a> 
    <a href="deletebank.php">Delete Bank</a>
    <a href="topay-check_status.php">TopPay Checker</a>
    <a class="active" href="mannullywithdraw.php">Manual Withdraw</a>
    <a href="logout.php" style="margin-top: 20px; color: #fca5a5;">Logout</a>
  </nav>
</div>

<div class="main">
  <div class="topbar">
    <div class="title">Quick Manual Payout (LPPAY)</div>
  </div>

  <div class="panel">
    <h3>Send Payment to Bank</h3>
    <?php if ($alertMessage): ?>
        <div class="alert alert-<?= $alertType ?>">
            <?= $alertMessage ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="">
        <div class="row">
            <div class="form-group">
                <label>Order ID (Auto-Generated)</label>
                <input type="text" name="order_no" class="form-control" value="<?= $autoOrderId ?>" readonly>
            </div>

            <div class="form-group">
                <label>Transfer Amount (₹)</label>
                <input type="number" step="0.01" name="amount" class="form-control" placeholder="E.g. 500" required>
            </div>

            <div class="form-group">
                <label>Account Holder Name</label>
                <input type="text" name="account_name" class="form-control" placeholder="Rahul Kumar" required>
            </div>

            <div class="form-group">
                <label>Bank Account Number</label>
                <input type="number" name="account_number" class="form-control" placeholder="123456789012" required>
            </div>

            <div class="form-group">
                <label>IFSC Code</label>
                <input type="text" name="ifsc_code" class="form-control" placeholder="SBIN0001234" required>
            </div>

            <div class="form-group">
                <label>Bank Name</label>
                <input type="text" name="bank_name" class="form-control" placeholder="State Bank of India" required>
            </div>
        </div>

        <button type="submit" name="send_payout" class="btn" onclick="return confirm('Confirm sending amount to this bank account?')">
            <svg class="svg-icon" viewBox="0 0 24 24" style="color: white; margin-right: 5px;"><path d="M22 2L11 13"></path><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
            Send Amount To Bank
        </button>
    </form>
  </div>

  <div class="panel">
    <h3>Recent Payout History</h3>
    
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Date & Time</th>
                    <th>Order ID</th>
                    <th>Account Name</th>
                    <th>Account No.</th>
                    <th>Amount</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($historyList) > 0): ?>
                    <?php foreach ($historyList as $history): ?>
                        <tr>
                            <td><?= date('d M Y, h:i A', strtotime($history['created_at'])) ?></td>
                            <td><strong><?= htmlspecialchars($history['order_no']) ?></strong></td>
                            <td><?= htmlspecialchars($history['account_name']) ?></td>
                            <td><?= htmlspecialchars($history['account_number']) ?></td>
                            <td style="font-weight:bold;">₹<?= number_format($history['amount'], 2) ?></td>
                            <td><span class="badge badge-warning"><?= htmlspecialchars($history['status']) ?></span></td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="6" style="text-align: center; color: #6b7280; padding: 20px;">
                            No manual payouts found. Create a table `manual_payouts` in database to see history here.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
  </div>

</div>

</body>
</html>