<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();

// Ensure Settings Table Exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        setting_key VARCHAR(50) PRIMARY KEY,
        setting_value TEXT
    )");

    // Seed default values if not exist
    $defaults = [
        'sms_api_key' => 'n4YfIKpTspjvQUhhtnOG',
        'sms_sender_id' => 'KHATIFOODB',
        'sms_url_one' => 'http://bulksmsbd.net/api/smsapi',
        'sms_url_many' => 'http://bulksmsbd.net/api/smsapimany',
        'sms_balance_url' => 'http://bulksmsbd.net/api/getBalanceApi'
    ];

    foreach ($defaults as $key => $val) {
        $stmt = $pdo->prepare("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES (?, ?)");
        $stmt->execute([$key, $val]);
    }

} catch (PDOException $e) {
    die("DB Setup Error: " . $e->getMessage());
}

$message = '';
$error = '';

// Handle Form Submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $settings_to_update = [
        'sms_api_key' => $_POST['sms_api_key'] ?? '',
        'sms_sender_id' => $_POST['sms_sender_id'] ?? '',
        'sms_url_one' => $_POST['sms_url_one'] ?? '',
        'sms_url_many' => $_POST['sms_url_many'] ?? '',
        'sms_balance_url' => $_POST['sms_balance_url'] ?? ''
    ];

    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");

        foreach ($settings_to_update as $key => $val) {
            $stmt->execute([$key, $val]);
        }
        $pdo->commit();
        $message = "Settings updated successfully.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Error updating settings: " . $e->getMessage();
    }
}

// Fetch Current Settings
$current_settings = [];
try {
    $stmt = $pdo->query("SELECT * FROM settings");
    while ($row = $stmt->fetch()) {
        $current_settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (PDOException $e) {
}

$pageTitle = "API Settings - SMS Admin";
include '../includes/header.php';
?>

<?php include '../includes/sidebar.php'; ?>

<?php include '../includes/navbar.php'; ?>

<div class="page-header">
    <h1 class="page-title">API Settings</h1>
    <div>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="javascript:void(0)">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">API Settings</li>
        </ol>
    </div>
</div>

<div class="row">
    <div class="col-xl-12 col-lg-12">
        <?php if (!empty($message)): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <div class="card mb-4">
            <div class="card-header">SMS Gateway Configuration</div>
            <div class="card-body">
                <form method="POST">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">API Key</label>
                            <input type="text" name="sms_api_key" class="form-control"
                                value="<?php echo htmlspecialchars($current_settings['sms_api_key'] ?? ''); ?>"
                                required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sender ID</label>
                            <input type="text" name="sms_sender_id" class="form-control"
                                value="<?php echo htmlspecialchars($current_settings['sms_sender_id'] ?? ''); ?>"
                                required>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Single SMS URL</label>
                        <input type="text" name="sms_url_one" class="form-control"
                            value="<?php echo htmlspecialchars($current_settings['sms_url_one'] ?? ''); ?>" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Bulk SMS URL</label>
                        <input type="text" name="sms_url_many" class="form-control"
                            value="<?php echo htmlspecialchars($current_settings['sms_url_many'] ?? ''); ?>" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Balance Check URL</label>
                        <input type="text" name="sms_balance_url" class="form-control"
                            value="<?php echo htmlspecialchars($current_settings['sms_balance_url'] ?? ''); ?>"
                            required>
                    </div>

                    <button type="submit" class="btn btn-primary">Save Settings</button>
                </form>
            </div>
        </div>
    </div>
</div>

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