<?php
require_once __DIR__ . '/../config/database.php';

requireLogin();
requireAnyRole(['admin', 'super_admin']);

$db = Database::getInstance();
$errors = [];
$success = false;

// Load WhatsApp settings with fallback if table doesn't exist
$settings = [];
$settingsTableExists = true;
try {
    $settingsRows = $db->getAll("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'whatsapp_%'");
    foreach ($settingsRows as $row) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    $settingsTableExists = false;
    $settings = [
        'whatsapp_enabled' => '0',
        'whatsapp_api_key' => '',
        'whatsapp_phone_number_id' => '',
        'whatsapp_webhook_url' => '',
        'whatsapp_business_account_id' => '',
        'whatsapp_version' => 'v18.0',
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $allowed = [
        'whatsapp_enabled',
        'whatsapp_api_key',
        'whatsapp_phone_number_id',
        'whatsapp_webhook_url',
        'whatsapp_business_account_id',
        'whatsapp_version',
    ];

    try {
        foreach ($allowed as $key) {
            $value = $_POST[$key] ?? '';
            if ($key === 'whatsapp_enabled') {
                $value = $value ? '1' : '0';
            }
            $db->query(
                "INSERT INTO settings (setting_key, setting_value) VALUES (?, ?)
                 ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)",
                [$key, $value]
            );
        }
        $_SESSION['flash']['success'] = 'WhatsApp settings updated successfully.';
    } catch (Exception $e) {
        $_SESSION['flash']['danger'] = 'Settings table does not exist. Please create it first.';
    }
    header('Location: whatsapp.php');
    exit;
}

$pageTitle = 'WhatsApp Integration';
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
  <div>
    <h1 class="h4 mb-0">WhatsApp Integration</h1>
    <p class="text-muted mb-0">Configure WhatsApp Business API settings</p>
  </div>
</div>

<?php if (!$settingsTableExists && !isset($_SESSION['flash']['danger'])): ?>
    <div class="alert alert-warning">
        <strong>Note:</strong> The <code>settings</code> table does not exist. Please run the following SQL to create it:
        <pre class="mt-2 mb-0">CREATE TABLE IF NOT EXISTS settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    setting_key VARCHAR(100) NOT NULL UNIQUE,
    setting_value TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);</pre>
    </div>
<?php endif; ?>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
      <ul class="mb-0">
        <?php foreach ($errors as $error): ?>
          <li><?php echo htmlspecialchars($error); ?></li>
        <?php endforeach; ?>
      </ul>
    </div>
<?php endif; ?>

<div class="card">
  <div class="card-body">
    <?php if (!$settingsTableExists): ?>
        <div class="alert alert-warning">Please create the settings table before editing WhatsApp settings.</div>
    <?php else: ?>
        <form method="post" action="">
          <h5 class="mb-3">General Settings</h5>
          <div class="mb-3">
            <div class="form-check form-switch">
              <input class="form-check-input" type="checkbox" name="whatsapp_enabled" id="whatsapp_enabled" value="1" <?php echo ($settings['whatsapp_enabled'] ?? '0') === '1' ? 'checked' : ''; ?>>
              <label class="form-check-label" for="whatsapp_enabled">Enable WhatsApp Integration</label>
            </div>
          </div>

          <hr class="my-4">

          <h5 class="mb-3">API Configuration</h5>
          <div class="row mb-3">
            <div class="col-md-6">
              <label for="whatsapp_api_key" class="form-label">API Key (Access Token)</label>
              <input type="password" name="whatsapp_api_key" id="whatsapp_api_key" class="form-control" value="<?php echo htmlspecialchars($settings['whatsapp_api_key'] ?? ''); ?>">
              <small class="text-muted">Get this from Meta for Developers</small>
            </div>
            <div class="col-md-6">
              <label for="whatsapp_phone_number_id" class="form-label">Phone Number ID</label>
              <input type="text" name="whatsapp_phone_number_id" id="whatsapp_phone_number_id" class="form-control" value="<?php echo htmlspecialchars($settings['whatsapp_phone_number_id'] ?? ''); ?>">
              <small class="text-muted">Your WhatsApp Business Phone Number ID</small>
            </div>
          </div>

          <div class="row mb-3">
            <div class="col-md-6">
              <label for="whatsapp_business_account_id" class="form-label">Business Account ID</label>
              <input type="text" name="whatsapp_business_account_id" id="whatsapp_business_account_id" class="form-control" value="<?php echo htmlspecialchars($settings['whatsapp_business_account_id'] ?? ''); ?>">
              <small class="text-muted">Your WhatsApp Business Account ID</small>
            </div>
            <div class="col-md-6">
              <label for="whatsapp_version" class="form-label">API Version</label>
              <input type="text" name="whatsapp_version" id="whatsapp_version" class="form-control" value="<?php echo htmlspecialchars($settings['whatsapp_version'] ?? 'v18.0'); ?>">
              <small class="text-muted">Meta Graph API version</small>
            </div>
          </div>

          <div class="mb-3">
            <label for="whatsapp_webhook_url" class="form-label">Webhook URL</label>
            <input type="url" name="whatsapp_webhook_url" id="whatsapp_webhook_url" class="form-control" value="<?php echo htmlspecialchars($settings['whatsapp_webhook_url'] ?? ''); ?>" placeholder="https://yourdomain.com/webhooks/whatsapp">
            <small class="text-muted">URL to receive webhook events from WhatsApp</small>
          </div>

          <hr class="my-4">

          <h5 class="mb-3">Test Connection</h5>
          <div class="mb-3">
            <button type="button" class="btn btn-outline-primary" onclick="testWhatsAppConnection()">
              <i class="fas fa-plug me-2"></i>Test Connection
            </button>
            <div id="testResult" class="mt-2"></div>
          </div>

          <div class="d-flex justify-content-end">
            <button type="submit" class="btn btn-primary">
              <i class="fas fa-save me-2"></i>Save Settings
            </button>
          </div>
        </form>
    <?php endif; ?>
  </div>
</div>

<script>
function testWhatsAppConnection() {
    const resultDiv = document.getElementById('testResult');
    resultDiv.innerHTML = '<div class="spinner-border spinner-border-sm me-2"></div>Testing...';
    
    // This would normally make an AJAX call to test the connection
    setTimeout(() => {
        resultDiv.innerHTML = '<div class="alert alert-info">Connection test not implemented yet.</div>';
    }, 1000);
}
</script>

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