<?php
require_once 'config.php'; // This already starts the session

// -------------------------------------------------------------------
// SMS Function (bulksmsbd.net)
// -------------------------------------------------------------------
function sendSMS($phone, $name, $order_id, $status, $courier_link, $pdo) {
    $api_key = getSetting('bulksms_api_key', $pdo);
    $sender_id = getSetting('bulksms_sender_id', $pdo);
    $api_url = getSetting('bulksms_api_url', $pdo);
    if (!$api_key || !$sender_id || !$api_url) return false;
    
    $message = "Dear $name, your order #$order_id is now *$status*. ";
    if ($status == 'shipped' && !empty($courier_link)) {
        $message .= "Track your shipment: $courier_link";
    } elseif ($status == 'confirmed') {
        $message .= "We will process and ship soon. Thank you for shopping with HomoeoCare.";
    } else {
        $message .= "Thank you for choosing HomoeoCare.";
    }
    
    $postData = [
        'api_key' => $api_key,
        'senderid' => $sender_id,
        'number' => $phone,
        'message' => $message
    ];
    
    $ch = curl_init($api_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

// -------------------------------------------------------------------
// Admin Authentication
// -------------------------------------------------------------------
$admin_hash = getSetting('admin_password_hash', $pdo);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    if (password_verify($_POST['password'], $admin_hash)) {
        $_SESSION['admin_logged'] = true;
    } else {
        $login_error = "Wrong password";
    }
}
if (!isset($_SESSION['admin_logged']) || $_SESSION['admin_logged'] !== true) {
    echo '<!DOCTYPE html><html><head><title>Admin Login</title><link rel="stylesheet" href="style.css"><style>.login-box{max-width:400px;margin:80px auto;background:white;padding:30px;border-radius:28px;}</style></head><body><div class="container"><div class="login-box"><h2>Admin Login</h2>';
    if (isset($login_error)) echo "<div class='alert error'>$login_error</div>";
    echo '<form method="post"><input type="password" name="password" placeholder="Password" required><button type="submit" name="login" class="btn-buy">Login</button></form></div></div></body></html>';
    exit;
}

// Handle logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

// -------------------------------------------------------------------
// Handle POST Actions
// -------------------------------------------------------------------
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update potency prices
    if (isset($_POST['update_prices'])) {
        foreach ($_POST['price'] as $p => $price) {
            $stmt = $pdo->prepare("UPDATE potency_prices SET price = ? WHERE potency_number = ?");
            $stmt->execute([(float)$price, (int)$p]);
        }
        $msg = "Potency prices updated!";
    }
    
    // Add single medicine
    if (isset($_POST['add_medicine'])) {
        $name = trim($_POST['medicine_name']);
        if ($name) {
            $stmt = $pdo->prepare("INSERT IGNORE INTO medicines (name) VALUES (?)");
            $stmt->execute([$name]);
            $msg = $stmt->rowCount() ? "Medicine added." : "Duplicate or invalid.";
        }
    }
    
    // Bulk add medicines
    if (isset($_POST['bulk_medicines'])) {
        $lines = explode("\n", $_POST['bulk_list']);
        $count = 0;
        foreach ($lines as $line) {
            $name = trim($line);
            if ($name !== '') {
                $stmt = $pdo->prepare("INSERT IGNORE INTO medicines (name) VALUES (?)");
                $stmt->execute([$name]);
                if ($stmt->rowCount()) $count++;
            }
        }
        $msg = "$count new medicines added (duplicates ignored).";
    }
    
    // Delete medicine
    if (isset($_POST['delete_medicine'])) {
        $pdo->prepare("DELETE FROM medicines WHERE id = ?")->execute([(int)$_POST['med_id']]);
        $msg = "Medicine deleted.";
    }
    
    // Save combo
    if (isset($_POST['save_combo'])) {
        $med_id = (int)$_POST['combo_medicine'];
        $start = (int)$_POST['combo_start'];
        $end = (int)$_POST['combo_end'];
        $price = (float)$_POST['combo_price'];
        $stmt = $pdo->prepare("INSERT INTO combos (medicine_id, potency_start, potency_end, package_price) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE package_price = ?");
        $stmt->execute([$med_id, $start, $end, $price, $price]);
        $msg = "Combo saved.";
    }
    
    // Delete combo
    if (isset($_POST['delete_combo'])) {
        $pdo->prepare("DELETE FROM combos WHERE id = ?")->execute([(int)$_POST['combo_id']]);
        $msg = "Combo removed.";
    }
    
    // Update order status + courier link + SMS trigger
    if (isset($_POST['update_order_status'])) {
        $order_id = (int)$_POST['order_id'];
        $new_status = $_POST['status'];
        $courier_link = trim($_POST['courier_link'] ?? '');
        
        $stmt = $pdo->prepare("SELECT order_status, customer_phone, customer_name FROM orders WHERE id = ?");
        $stmt->execute([$order_id]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($order) {
            $old_status = $order['order_status'];
            $update = $pdo->prepare("UPDATE orders SET order_status = ?, courier_tracking_link = ? WHERE id = ?");
            $update->execute([$new_status, $courier_link, $order_id]);
            
            // Send SMS if status changed to 'confirmed' or 'shipped'
            if (($new_status == 'confirmed' || $new_status == 'shipped') && $old_status != $new_status) {
                sendSMS($order['customer_phone'], $order['customer_name'], $order_id, $new_status, $courier_link, $pdo);
            }
            $msg = "Order #$order_id updated to $new_status";
        } else {
            $msg = "Order not found.";
        }
    }
    
    // Update WhatsApp number
    if (isset($_POST['update_whatsapp'])) {
        $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'admin_whatsapp'")->execute([$_POST['whatsapp_number']]);
        $msg = "WhatsApp number updated.";
    }
    
    // Update SMS API credentials
    if (isset($_POST['update_sms'])) {
        $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'bulksms_api_key'")->execute([$_POST['bulksms_api_key']]);
        $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'bulksms_sender_id'")->execute([$_POST['bulksms_sender_id']]);
        $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = 'bulksms_api_url'")->execute([$_POST['bulksms_api_url']]);
        $msg = "SMS API credentials updated.";
    }
}

// -------------------------------------------------------------------
// Fetch Data
// -------------------------------------------------------------------
$medicines = $pdo->query("SELECT * FROM medicines ORDER BY name")->fetchAll();
$prices = getAllPotencyPrices($pdo);
$combos = $pdo->query("SELECT c.*, m.name as medicine_name FROM combos c JOIN medicines m ON c.medicine_id = m.id")->fetchAll();
$orders = $pdo->query("SELECT * FROM orders ORDER BY id DESC")->fetchAll();

// Dashboard stats
$total_orders = count($orders);
$pending_orders = count(array_filter($orders, fn($o) => $o['order_status'] == 'pending'));
$total_revenue = array_sum(array_column($orders, 'total_amount'));

$whatsapp = getSetting('admin_whatsapp', $pdo);
$sms_api_key = getSetting('bulksms_api_key', $pdo);
$sms_sender_id = getSetting('bulksms_sender_id', $pdo);
$sms_api_url = getSetting('bulksms_api_url', $pdo);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel – HomoeoCare</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .dashboard-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: linear-gradient(135deg, #2c5e2e, #4a8c4c);
            color: white;
            padding: 20px;
            border-radius: 24px;
            text-align: center;
        }
        .stat-card h3 { font-size: 2rem; margin: 0; }
        .stat-card p { margin: 10px 0 0; opacity: 0.9; }
        .admin-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 24px;
            margin-top: 20px;
        }
        .card {
            background: white;
            border-radius: 24px;
            padding: 20px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.05);
            border: 1px solid #e0ecdf;
        }
        .card h2 {
            margin-top: 0;
            font-size: 1.4rem;
            border-bottom: 2px solid #cbe5cb;
            padding-bottom: 10px;
            margin-bottom: 18px;
        }
        .full-width { grid-column: 1 / -1; }
        .med-item { display: flex; justify-content: space-between; padding: 8px; border-bottom: 1px solid #e2eddf; }
        .order-table { width: 100%; border-collapse: collapse; overflow-x: auto; display: block; }
        .order-table th, .order-table td { padding: 10px; border-bottom: 1px solid #e0ecdf; text-align: left; }
        .status-badge { display: inline-block; padding: 4px 12px; border-radius: 40px; font-size: 0.8rem; font-weight: bold; }
        .status-pending { background: #ffc107; color: #333; }
        .status-confirmed { background: #28a745; color: white; }
        .status-shipped { background: #17a2b8; color: white; }
        .status-delivered { background: #6f42c1; color: white; }
        .status-cancelled { background: #dc3545; color: white; }
        input, select, textarea { border-radius: 40px; padding: 8px 12px; border: 1px solid #cde0cd; width: 100%; margin-bottom: 10px; }
        button { background: #2c5e2e; color: white; border: none; padding: 8px 18px; border-radius: 40px; cursor: pointer; }
        button:hover { background: #1f4521; }
        .responsive-table { overflow-x: auto; }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>⚙️ HomoeoCare Admin Panel</h1>
        <nav>
            <a href="shop.php">← Shop</a>
            <a href="cart.php">Cart</a>
            <a href="track.php">Track Orders</a>
            <a href="?logout=1" onclick="return confirm('Logout?')">Logout</a>
        </nav>
    </header>
    
    <?php if ($msg): ?>
        <div class="alert success"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    
    <!-- Dashboard Stats -->
    <div class="dashboard-stats">
        <div class="stat-card"><h3><?= $total_orders ?></h3><p>Total Orders</p></div>
        <div class="stat-card"><h3><?= $pending_orders ?></h3><p>Pending Orders</p></div>
        <div class="stat-card"><h3><?= number_format($total_revenue, 2) ?> BDT</h3><p>Total Revenue</p></div>
    </div>
    
    <div class="admin-grid">
        <!-- WhatsApp Settings -->
        <div class="card">
            <h2>📞 WhatsApp Number</h2>
            <form method="post">
                <input type="text" name="whatsapp_number" value="<?= htmlspecialchars($whatsapp) ?>" required>
                <button type="submit" name="update_whatsapp">Save</button>
            </form>
        </div>
        
        <!-- SMS API Settings -->
        <div class="card">
            <h2>📱 SMS API (bulksmsbd.net)</h2>
            <form method="post">
                <input type="text" name="bulksms_api_key" value="<?= htmlspecialchars($sms_api_key) ?>" placeholder="API Key">
                <input type="text" name="bulksms_sender_id" value="<?= htmlspecialchars($sms_sender_id) ?>" placeholder="Sender ID">
                <input type="text" name="bulksms_api_url" value="<?= htmlspecialchars($sms_api_url) ?>" placeholder="API URL">
                <button type="submit" name="update_sms">Save SMS Settings</button>
            </form>
        </div>
        
        <!-- Potency Prices -->
        <div class="card">
            <h2>💰 Potency Prices (M/1–M/30)</h2>
            <form method="post">
                <div style="max-height: 200px; overflow-y: auto;">
                    <?php for ($i=1; $i<=30; $i++): ?>
                        <label>M/<?= $i ?>: <input type="number" step="0.01" name="price[<?= $i ?>]" value="<?= $prices[$i] ?>" style="width:80px; display:inline-block;"></label><br>
                    <?php endfor; ?>
                </div>
                <button type="submit" name="update_prices">Update Prices</button>
            </form>
        </div>
        
        <!-- Medicines Management -->
        <div class="card">
            <h2>➕ Manage Medicines</h2>
            <form method="post">
                <input type="text" name="medicine_name" placeholder="Single medicine name" required>
                <button type="submit" name="add_medicine">Add Medicine</button>
            </form>
            <h3>📦 Bulk Add (one per line)</h3>
            <form method="post">
                <textarea name="bulk_list" rows="5" placeholder="Aconite Nap&#10;Belladonna&#10;Arnica"></textarea>
                <button type="submit" name="bulk_medicines">Bulk Insert</button>
            </form>
            <h3>📋 Existing Medicines (<?= count($medicines) ?>)</h3>
            <div style="max-height: 250px; overflow-y: auto;">
                <?php foreach ($medicines as $m): ?>
                    <div class="med-item">
                        <?= htmlspecialchars($m['name']) ?>
                        <form method="post" style="display:inline;">
                            <input type="hidden" name="med_id" value="<?= $m['id'] ?>">
                            <button type="submit" name="delete_medicine" onclick="return confirm('Delete this medicine?')">🗑️</button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <!-- Combo Management -->
        <div class="card">
            <h2>🔥 Combo Packages</h2>
            <form method="post">
                <select name="combo_medicine" required>
                    <option value="">Select Medicine</option>
                    <?php foreach ($medicines as $m): ?>
                        <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="number" name="combo_start" min="1" max="30" placeholder="Start M/" required>
                <input type="number" name="combo_end" min="1" max="30" placeholder="End M/" required>
                <input type="number" step="0.01" name="combo_price" placeholder="Package price" required>
                <button type="submit" name="save_combo">Save Combo</button>
            </form>
            <h3>Existing Combos</h3>
            <?php foreach ($combos as $c): ?>
                <div class="med-item">
                    <?= htmlspecialchars($c['medicine_name']) ?> M/<?= $c['potency_start'] ?>–M/<?= $c['potency_end'] ?> = <?= number_format($c['package_price'],2) ?> BDT
                    <form method="post" style="display:inline;">
                        <input type="hidden" name="combo_id" value="<?= $c['id'] ?>">
                        <button type="submit" name="delete_combo" onclick="return confirm('Delete combo?')">🗑️</button>
                    </form>
                </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Orders Section (full width) -->
        <div class="card full-width">
            <h2>📦 Orders & Tracking</h2>
            <div class="responsive-table">
                <table class="order-table">
                    <thead>
                        <tr><th>ID</th><th>Customer</th><th>Phone</th><th>Total</th><th>Payment</th><th>TrxID</th><th>Status</th><th>Courier Link</th><th>Actions</th></tr>
                    </thead>
                    <tbody>
                        <?php foreach ($orders as $order): ?>
                        <tr>
                            <td><?= $order['id'] ?></td>
                            <td><?= htmlspecialchars($order['customer_name']) ?></td>
                            <td><?= $order['customer_phone'] ?></td>
                            <td><?= number_format($order['total_amount'],2) ?> BDT</td>
                            <td><?= $order['payment_method'] ?></td>
                            <td><small><?= htmlspecialchars($order['transaction_id'] ?? '—') ?></small></td>
                            <td><span class="status-badge status-<?= $order['order_status'] ?>"><?= ucfirst($order['order_status']) ?></span></td>
                            <td><?= $order['courier_tracking_link'] ? '<a href="'.$order['courier_tracking_link'].'" target="_blank">Track</a>' : '—' ?></td>
                            <td>
                                <form method="post" style="display: flex; gap: 5px; flex-wrap: wrap;">
                                    <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                                    <select name="status">
                                        <option value="pending" <?= $order['order_status']=='pending' ? 'selected' : '' ?>>pending</option>
                                        <option value="confirmed" <?= $order['order_status']=='confirmed' ? 'selected' : '' ?>>confirmed</option>
                                        <option value="shipped" <?= $order['order_status']=='shipped' ? 'selected' : '' ?>>shipped</option>
                                        <option value="delivered" <?= $order['order_status']=='delivered' ? 'selected' : '' ?>>delivered</option>
                                        <option value="cancelled" <?= $order['order_status']=='cancelled' ? 'selected' : '' ?>>cancelled</option>
                                    </select>
                                    <input type="text" name="courier_link" placeholder="Tracking URL" value="<?= htmlspecialchars($order['courier_tracking_link'] ?? '') ?>" style="width: 180px;">
                                    <button type="submit" name="update_order_status">Update</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
</html>