<?php
// config.php - Dynamic Database and SMS Configuration
// This file reads settings from admin_settings table

// ============================================
// DATABASE CONFIGURATION (Static)
// ============================================
$db_host = 'localhost';
$db_user = 'drmdferdous_dflms';
$db_pass = 'drmdferdous_dflms';
$db_name = 'drmdferdous_dflms';

// Create connection
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Set character set to UTF-8
mysqli_set_charset($conn, "utf8mb4");

// ============================================
// LOAD DYNAMIC SETTINGS FROM DATABASE
// ============================================
function loadSettings() {
    global $conn;
    $settings = array();
    
    // Check if admin_settings table exists
    $table_check = mysqli_query($conn, "SHOW TABLES LIKE 'admin_settings'");
    if (mysqli_num_rows($table_check) == 0) {
        // Create table if it doesn't exist
        mysqli_query($conn, "CREATE TABLE IF NOT EXISTS admin_settings (
            id INT AUTO_INCREMENT PRIMARY KEY,
            setting_key VARCHAR(100) UNIQUE NOT NULL,
            setting_value TEXT,
            setting_type ENUM('text','number','boolean','json','image') DEFAULT 'text',
            description VARCHAR(255),
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )");
        
        // Insert default settings
        mysqli_query($conn, "INSERT IGNORE INTO admin_settings (setting_key, setting_value, setting_type, description) VALUES
            ('min_booking_days', '3', 'number', 'Minimum days in advance for booking'),
            ('max_booking_days', '30', 'number', 'Maximum days in advance for booking'),
            ('slot_duration', '30', 'number', 'Default slot duration in minutes'),
            ('enable_sms', 'true', 'boolean', 'Enable SMS notifications'),
            ('admin_phone', '01775121112', 'text', 'Admin phone number for alerts'),
            ('booking_fees', '{\"regular\":200,\"special\":500,\"free_medicine\":100}', 'json', 'Fee structure for patient categories'),
            ('sms_api_key', '', 'text', 'bulksmsbd.net API Key'),
            ('sms_sender_id', '8809617610000', 'text', 'bulksmsbd.net Sender ID'),
            ('sms_username', '', 'text', 'bulksmsbd.net Username'),
            ('sms_password', '', 'text', 'bulksmsbd.net Password'),
            ('sms_api_url', 'https://bulksmsbd.net/api/smsapi', 'text', 'bulksmsbd.net API URL'),
            ('sunday_start', '09:00', 'text', 'Sunday working start time'),
            ('sunday_end', '17:00', 'text', 'Sunday working end time'),
            ('monday_start', '09:00', 'text', 'Monday working start time'),
            ('monday_end', '17:00', 'text', 'Monday working end time'),
            ('tuesday_start', '09:00', 'text', 'Tuesday working start time'),
            ('tuesday_end', '17:00', 'text', 'Tuesday working end time'),
            ('wednesday_start', '09:00', 'text', 'Wednesday working start time'),
            ('wednesday_end', '17:00', 'text', 'Wednesday working end time'),
            ('thursday_start', '09:00', 'text', 'Thursday working start time'),
            ('thursday_end', '17:00', 'text', 'Thursday working end time'),
            ('friday_start', '09:00', 'text', 'Friday working start time'),
            ('friday_end', '17:00', 'text', 'Friday working end time'),
            ('saturday_start', '09:00', 'text', 'Saturday working start time'),
            ('saturday_end', '17:00', 'text', 'Saturday working end time')
        ");
    }
    
    // Load all settings
    $result = mysqli_query($conn, "SELECT setting_key, setting_value, setting_type FROM admin_settings");
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $settings[$row['setting_key']] = array(
                'value' => $row['setting_value'],
                'type' => $row['setting_type']
            );
        }
    }
    
    return $settings;
}

// Load settings
$SETTINGS = loadSettings();

// ============================================
// DEFINE CONSTANTS FROM SETTINGS
// ============================================
// SMS Configuration
define('SMS_API_KEY', getSetting('sms_api_key', ''));
define('SMS_SENDER_ID', getSetting('sms_sender_id', '8809617610000'));
define('SMS_USERNAME', getSetting('sms_username', ''));
define('SMS_PASSWORD', getSetting('sms_password', ''));
define('SMS_API_URL', getSetting('sms_api_url', 'https://bulksmsbd.net/api/smsapi'));
define('ADMIN_PHONE', getSetting('admin_phone', '01775121112'));
define('ENABLE_SMS', getSetting('enable_sms', 'true') === 'true');

// Booking Configuration
define('MIN_BOOKING_DAYS', intval(getSetting('min_booking_days', 3)));
define('MAX_BOOKING_DAYS', intval(getSetting('max_booking_days', 30)));
define('DEFAULT_SLOT_DURATION', intval(getSetting('slot_duration', 30)));

// Fee Structure
$booking_fees = json_decode(getSetting('booking_fees', '{"regular":200,"special":500,"free_medicine":100}'), true);
if (!is_array($booking_fees)) {
    $booking_fees = array('regular' => 200, 'special' => 500, 'free_medicine' => 100);
}
define('REGULAR_FEE', isset($booking_fees['regular']) ? $booking_fees['regular'] : 200);
define('SPECIAL_FEE', isset($booking_fees['special']) ? $booking_fees['special'] : 500);
define('FREE_MEDICINE_FEE', isset($booking_fees['free_medicine']) ? $booking_fees['free_medicine'] : 100);

// ============================================
// HELPER FUNCTIONS
// ============================================
function getSetting($key, $default = '') {
    global $SETTINGS;
    if (isset($SETTINGS[$key])) {
        return $SETTINGS[$key]['value'];
    }
    return $default;
}

function updateSetting($key, $value) {
    global $conn;
    $value = mysqli_real_escape_string($conn, $value);
    $query = "UPDATE admin_settings SET setting_value = '$value', updated_at = NOW() WHERE setting_key = '$key'";
    return mysqli_query($conn, $query);
}

function getWorkingHours($day) {
    $start = getSetting(strtolower($day) . '_start', '09:00');
    $end = getSetting(strtolower($day) . '_end', '17:00');
    return array('start' => $start, 'end' => $end);
}

// ============================================
// SMS FUNCTIONS
// ============================================
function sendSMS($to, $message) {
    if (!ENABLE_SMS) {
        error_log("SMS disabled. Would have sent to $to: $message");
        return false;
    }
    
    $apiKey = SMS_API_KEY;
    $senderId = SMS_SENDER_ID;
    $url = SMS_API_URL;
    
    // Try API Key method first
    if (!empty($apiKey)) {
        $data = array(
            "api_key" => $apiKey,
            "senderid" => $senderId,
            "number" => $to,
            "message" => $message
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        error_log("SMS (API) to $to - Response: " . $response);
        error_log("SMS (API) to $to - HTTP Code: " . $http_code);
        
        if ($curl_error) {
            error_log("SMS (API) to $to - CURL Error: " . $curl_error);
        }
        
        return $response;
    }
    
    // Try Username/Password method
    $username = SMS_USERNAME;
    $password = SMS_PASSWORD;
    
    if (!empty($username) && !empty($password)) {
        $data = array(
            "username" => $username,
            "password" => $password,
            "senderid" => $senderId,
            "number" => $to,
            "message" => $message
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        error_log("SMS (Auth) to $to - Response: " . $response);
        return $response;
    }
    
    error_log("SMS failed: No credentials configured for $to");
    return false;
}

function sendAppointmentSMS($patient_name, $patient_phone, $chamber_name, $date, $time, $fee = 0) {
    if (!ENABLE_SMS) {
        return false;
    }
    
    // Patient confirmation message
    $patient_msg = "Dear $patient_name, Your appointment is confirmed on $date at $time at $chamber_name. Thank you.";
    
    // Admin alert message
    $admin_msg = "New booking: $patient_name on $date at $time at $chamber_name. Fee: $fee Tk.";
    
    // Send to patient
    $patient_result = sendSMS($patient_phone, $patient_msg);
    
    // Send to admin
    $admin_result = sendSMS(ADMIN_PHONE, $admin_msg);
    
    return array(
        'patient' => $patient_result,
        'admin' => $admin_result
    );
}

function sendFreeMedicineCampSMS($patient_name, $patient_phone, $chamber_name, $date, $time) {
    if (!ENABLE_SMS) {
        return false;
    }
    
    $msg = "Dear $patient_name, Your Free Medicine Camp appointment is confirmed on $date at $time at $chamber_name. Bring previous prescriptions.";
    return sendSMS($patient_phone, $msg);
}

function sendReminderSMS($patient_name, $patient_phone, $chamber_name, $date, $time) {
    if (!ENABLE_SMS) {
        return false;
    }
    
    $msg = "Reminder: Dear $patient_name, you have an appointment tomorrow at $time at $chamber_name. Please be on time.";
    return sendSMS($patient_phone, $msg);
}

function sendBulkSMS($numbers, $message) {
    if (!ENABLE_SMS) {
        return false;
    }
    
    $results = array();
    foreach ($numbers as $number) {
        $results[] = sendSMS($number, $message);
    }
    return $results;
}

// ============================================
// SESSION START
// ============================================
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// ============================================
// TEST SMS FUNCTION (Optional)
// ============================================
function testSMSConfiguration() {
    global $conn;
    
    echo "<h2>SMS Configuration Test</h2>";
    echo "<pre>";
    echo "SMS Enabled: " . (ENABLE_SMS ? "Yes" : "No") . "\n";
    echo "API Key: " . (SMS_API_KEY ? "Set" : "Not Set") . "\n";
    echo "Sender ID: " . SMS_SENDER_ID . "\n";
    echo "Admin Phone: " . ADMIN_PHONE . "\n";
    echo "API URL: " . SMS_API_URL . "\n";
    echo "Username: " . (SMS_USERNAME ? "Set" : "Not Set") . "\n";
    echo "Password: " . (SMS_PASSWORD ? "Set" : "Not Set") . "\n";
    echo "</pre>";
    
    if (ENABLE_SMS && SMS_API_KEY) {
        echo "<p>Testing SMS to admin...</p>";
        $result = sendSMS(ADMIN_PHONE, "Test SMS from Doctor Portal. Configuration is working!");
        echo "Result: " . ($result ? "Sent" : "Failed") . "<br>";
        echo "Response: " . htmlspecialchars($result);
    } else {
        echo "<p style='color:orange'>SMS is disabled or not configured. Enable in admin_settings.</p>";
    }
}

// ============================================
// DEFAULT WORKING HOURS (for admin_config.php)
// ============================================
function getDefaultWorkingHours() {
    return array(
        'sunday' => array('start' => getSetting('sunday_start', '09:00'), 'end' => getSetting('sunday_end', '17:00')),
        'monday' => array('start' => getSetting('monday_start', '09:00'), 'end' => getSetting('monday_end', '17:00')),
        'tuesday' => array('start' => getSetting('tuesday_start', '09:00'), 'end' => getSetting('tuesday_end', '17:00')),
        'wednesday' => array('start' => getSetting('wednesday_start', '09:00'), 'end' => getSetting('wednesday_end', '17:00')),
        'thursday' => array('start' => getSetting('thursday_start', '09:00'), 'end' => getSetting('thursday_end', '17:00')),
        'friday' => array('start' => getSetting('friday_start', '09:00'), 'end' => getSetting('friday_end', '17:00')),
        'saturday' => array('start' => getSetting('saturday_start', '09:00'), 'end' => getSetting('saturday_end', '17:00'))
    );
}
?>