<?php
// ============================================
// COMPLETE CONFIGURATION FILE
// Doctor Portal - Database, SMS, & Settings
// ============================================

// ============================================
// 1. DATABASE CONFIGURATION
// ============================================
$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");

// ============================================
// 2. ERROR REPORTING (Production Ready)
// ============================================
// Uncomment for debugging
// error_reporting(E_ALL);
// ini_set('display_errors', 1);

// ============================================
// 3. 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
        $create_table = "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
        )";
        mysqli_query($conn, $create_table);
        
        // Insert default settings
        $default_settings = array(
            'min_booking_days' => array('3', 'number', 'Minimum days in advance for booking'),
            'max_booking_days' => array('30', 'number', 'Maximum days in advance for booking'),
            'slot_duration' => array('30', 'number', 'Default slot duration in minutes'),
            'enable_sms' => array('true', 'boolean', 'Enable SMS notifications'),
            'admin_phone' => array('01775121112', 'text', 'Admin phone number for alerts'),
            'booking_fees' => array('{"regular":200,"special":500,"free_medicine":100}', 'json', 'Fee structure for patient categories'),
            'sms_api_key' => array('', 'text', 'bulksmsbd.net API Key'),
            'sms_sender_id' => array('8809617610000', 'text', 'bulksmsbd.net Sender ID'),
            'sms_username' => array('', 'text', 'bulksmsbd.net Username'),
            'sms_password' => array('', 'text', 'bulksmsbd.net Password'),
            'sms_api_url' => array('https://bulksmsbd.net/api/smsapi', 'text', 'bulksmsbd.net API URL')
        );
        
        foreach ($default_settings as $key => $value) {
            $insert = "INSERT IGNORE INTO admin_settings (setting_key, setting_value, setting_type, description) 
                       VALUES ('$key', '{$value[0]}', '{$value[1]}', '{$value[2]}')";
            mysqli_query($conn, $insert);
        }
    }
    
    // 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();

// ============================================
// 4. 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 getStyle($key, $default = '') {
    global $conn;
    static $styles = null;
    
    if ($styles === null) {
        $styles = array();
        $result = mysqli_query($conn, "SELECT setting_key, setting_value FROM admin_settings");
        if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
                $styles[$row['setting_key']] = $row['setting_value'];
            }
        }
    }
    
    return isset($styles[$key]) && !empty($styles[$key]) ? $styles[$key] : $default;
}

// ============================================
// 5. DEFINE CONSTANTS FROM SETTINGS
// ============================================
// SMS Configuration
define('SMS_API_KEY', getSetting('sms_api_key', 'iBfvwrJ2Du5v9tqKROzJ'));
define('SMS_SENDER_ID', getSetting('sms_sender_id', '8809617625314'));
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);

// ============================================
// 6. SMS FUNCTIONS - COMPLETE & RELIABLE
// ============================================
if (!function_exists('sendSMS')) {
    
    /**
     * Send SMS using bulksmsbd.net API
     * 
     * @param string $to Phone number (with or without country code)
     * @param string $message SMS message (max 160 chars)
     * @return bool|string Returns true on success, false on failure
     */
    function sendSMS($to, $message) {
        // Log attempt for debugging
        error_log("SMS Attempt: To=$to, Message=" . substr($message, 0, 50) . "...");
        
        // Check if SMS is enabled
        if (!ENABLE_SMS) {
            error_log("SMS Disabled: Would have sent to $to");
            return false;
        }
        
        // Check API key
        if (empty(SMS_API_KEY)) {
            error_log("SMS Failed: No API Key configured");
            return false;
        }
        
        // Clean phone number - remove all non-numeric characters
        $to = preg_replace('/[^0-9]/', '', $to);
        
        // Format for Bangladesh: 88XXXXXXXXXX
        if (substr($to, 0, 2) == '88') {
            $to = substr($to, 2);
        }
        if (substr($to, 0, 1) == '0') {
            $to = substr($to, 1);
        }
        $to = '88' . $to;
        
        // Ensure phone number is valid length (11 digits after 88)
        if (strlen($to) != 13) {
            error_log("SMS Failed: Invalid phone number format - $to");
            return false;
        }
        
        // Truncate message if too long (160 chars for GSM)
        if (strlen($message) > 160) {
            $message = substr($message, 0, 157) . '...';
        }
        
        // Prepare API data
        $data = array(
            "api_key" => SMS_API_KEY,
            "senderid" => SMS_SENDER_ID,
            "number" => $to,
            "message" => $message
        );
        
        error_log("SMS Data: " . json_encode($data));
        
        // Initialize cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, SMS_API_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);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'DoctorPortal/1.0');
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_error = curl_error($ch);
        curl_close($ch);
        
        // Log response
        error_log("SMS Response: HTTP=$http_code, Response=" . substr($response, 0, 200));
        if ($curl_error) {
            error_log("SMS cURL Error: $curl_error");
        }
        
        // Check if successful
        $success = false;
        if ($response !== false && $response !== '') {
            // Check for success codes from bulksmsbd.net
            if (strpos($response, '1101') !== false || 
                strpos($response, 'Success') !== false ||
                strpos($response, 'success') !== false ||
                strpos($response, 'sent') !== false) {
                $success = true;
            }
            
            // Check JSON response
            $json_response = json_decode($response, true);
            if ($json_response) {
                if (isset($json_response['status']) && 
                    ($json_response['status'] == 'success' || 
                     $json_response['status'] == '1101' ||
                     $json_response['status'] == '1')) {
                    $success = true;
                }
                if (isset($json_response['code']) && $json_response['code'] == '1101') {
                    $success = true;
                }
            }
        }
        
        error_log("SMS Result: " . ($success ? '✅ SUCCESS' : '❌ FAILED'));
        return $success;
    }
}

if (!function_exists('sendAppointmentSMS')) {
    
    /**
     * Send appointment confirmation SMS to patient and admin
     * 
     * @param string $patient_name Patient's full name
     * @param string $patient_phone Patient's phone number
     * @param string $doctor_name Doctor's name
     * @param string $chamber_name Chamber name
     * @param string $date Appointment date (formatted)
     * @param string $time Appointment time (formatted)
     * @param float $fee Appointment fee
     * @return array Array with 'patient' and 'admin' status
     */
    function sendAppointmentSMS($patient_name, $patient_phone, $doctor_name, $chamber_name, $date, $time, $fee = 0) {
        error_log("=== sendAppointmentSMS START ===");
        error_log("Patient: $patient_name, Phone: $patient_phone");
        error_log("Doctor: $doctor_name, Chamber: $chamber_name");
        error_log("Date: $date, Time: $time, Fee: $fee");
        
        $results = array(
            'patient' => false,
            'admin' => false
        );
        
        if (!ENABLE_SMS) {
            error_log("SMS Disabled in sendAppointmentSMS");
            return $results;
        }
        
        if (empty(SMS_API_KEY)) {
            error_log("SMS API Key missing in sendAppointmentSMS");
            return $results;
        }
        
        // Clean phone number
        $clean_phone = preg_replace('/[^0-9]/', '', $patient_phone);
        if (substr($clean_phone, 0, 2) == '88') {
            $clean_phone = substr($clean_phone, 2);
        }
        if (substr($clean_phone, 0, 1) == '0') {
            $clean_phone = substr($clean_phone, 1);
        }
        $clean_phone = '88' . $clean_phone;
        
        // Patient confirmation SMS
        $patient_msg = "Dear $patient_name, Your appointment with Dr. $doctor_name is confirmed on $date at $time at $chamber_name. Thank you.";
        $patient_result = sendSMS($clean_phone, $patient_msg);
        $results['patient'] = $patient_result;
        error_log("Patient SMS: " . ($patient_result ? '✅ SUCCESS' : '❌ FAILED'));
        
        // Admin alert SMS
        $admin_msg = "New booking: $patient_name ($patient_phone) with Dr. $doctor_name on $date at $time at $chamber_name.";
        if ($fee > 0) {
            $admin_msg .= " Fee: $fee Tk.";
        }
        $admin_result = sendSMS(ADMIN_PHONE, $admin_msg);
        $results['admin'] = $admin_result;
        error_log("Admin SMS: " . ($admin_result ? '✅ SUCCESS' : '❌ FAILED'));
        
        error_log("=== sendAppointmentSMS END ===");
        return $results;
    }
}

if (!function_exists('sendFreeMedicineCampSMS')) {
    
    /**
     * Send Free Medicine Camp appointment SMS
     */
    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);
    }
}

if (!function_exists('sendReminderSMS')) {
    
    /**
     * Send appointment reminder SMS
     */
    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);
    }
}

if (!function_exists('sendBulkSMS')) {
    
    /**
     * Send bulk SMS to multiple numbers
     */
    function sendBulkSMS($numbers, $message) {
        if (!ENABLE_SMS) {
            return false;
        }
        
        $results = array();
        foreach ($numbers as $number) {
            $results[] = sendSMS($number, $message);
        }
        return $results;
    }
}

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

// ============================================
// 8. TIMEZONE SETTING
// ============================================
date_default_timezone_set('Asia/Dhaka');

// ============================================
// 9. DEBUG FUNCTION (Optional)
// ============================================
function debugLog($message, $data = null) {
    $log = date('Y-m-d H:i:s') . " - " . $message;
    if ($data !== null) {
        $log .= " - " . json_encode($data);
    }
    error_log($log);
}

// ============================================
// 10. TEST SMS FUNCTION (Comment out in production)
// ============================================
if (!function_exists('testSMSConfiguration')) {
    
    function testSMSConfiguration() {
        global $conn;
        
        echo "<div style='font-family: Arial, sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; background: #f8f9fa; border-radius: 12px;'>";
        echo "<h2>📱 SMS Configuration Test</h2>";
        echo "<hr>";
        
        echo "<h3>1. Configuration Status</h3>";
        echo "<table style='width:100%; border-collapse: collapse;'>";
        echo "<tr><td><strong>ENABLE_SMS:</strong></td><td>" . (ENABLE_SMS ? '✅ Yes' : '❌ No') . "</td></tr>";
        echo "<tr><td><strong>SMS_API_KEY:</strong></td><td>" . (SMS_API_KEY ? '✅ Set (' . substr(SMS_API_KEY, 0, 10) . '...)' : '❌ Not Set') . "</td></tr>";
        echo "<tr><td><strong>SMS_SENDER_ID:</strong></td><td>" . SMS_SENDER_ID . "</td></tr>";
        echo "<tr><td><strong>ADMIN_PHONE:</strong></td><td>" . ADMIN_PHONE . "</td></tr>";
        echo "<tr><td><strong>SMS_API_URL:</strong></td><td>" . SMS_API_URL . "</td></tr>";
        echo "</table>";
        
        echo "<h3>2. Function Check</h3>";
        echo "sendSMS: " . (function_exists('sendSMS') ? '✅ Available' : '❌ Not Available') . "<br>";
        echo "sendAppointmentSMS: " . (function_exists('sendAppointmentSMS') ? '✅ Available' : '❌ Not Available') . "<br>";
        
        echo "<h3>3. cURL Check</h3>";
        echo "cURL installed: " . (function_exists('curl_version') ? '✅ Yes' : '❌ No') . "<br>";
        if (function_exists('curl_version')) {
            $curl_version = curl_version();
            echo "cURL version: " . $curl_version['version'] . "<br>";
        }
        
        echo "<h3>4. Send Test SMS</h3>";
        if (ENABLE_SMS && SMS_API_KEY) {
            $test_number = ADMIN_PHONE;
            $test_message = "Test SMS from Doctor Portal. Server time: " . date('Y-m-d H:i:s');
            
            echo "Sending to: <strong>$test_number</strong><br>";
            echo "Message: <em>$test_message</em><br>";
            
            if (function_exists('sendSMS')) {
                $result = sendSMS($test_number, $test_message);
                echo "Result: " . ($result ? '✅ <span style="color:green;">Sent Successfully!</span>' : '❌ <span style="color:red;">Failed to Send</span>') . "<br>";
            } else {
                echo "❌ sendSMS function not available<br>";
            }
        } else {
            echo "❌ SMS is not properly configured.<br>";
            if (!ENABLE_SMS) echo "- SMS is disabled<br>";
            if (!SMS_API_KEY) echo "- API Key missing<br>";
        }
        
        echo "<h3>5. Database Settings</h3>";
        $settings_query = "SELECT setting_key, setting_value FROM admin_settings 
                           WHERE setting_key IN ('enable_sms', 'sms_api_key', 'sms_sender_id', 'admin_phone')";
        $settings_result = mysqli_query($conn, $settings_query);
        if ($settings_result) {
            echo "<table style='width:100%; border-collapse: collapse;'>";
            while ($row = mysqli_fetch_assoc($settings_result)) {
                $value = $row['setting_key'] == 'sms_api_key' && !empty($row['setting_value']) 
                        ? substr($row['setting_value'], 0, 10) . '...' 
                        : $row['setting_value'];
                echo "<tr><td><strong>" . $row['setting_key'] . ":</strong></td><td>" . htmlspecialchars($value) . "</td></tr>";
            }
            echo "</table>";
        } else {
            echo "No settings found or error: " . mysqli_error($conn);
        }
        
        echo "<hr>";
        echo "<a href='admin_config.php#settings' style='display:inline-block; padding:10px 20px; background:#1a5276; color:white; text-decoration:none; border-radius:8px;'>Go to Settings</a>";
        echo "</div>";
    }
}

// ============================================
// 11. DEFAULT WORKING HOURS
// ============================================
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'))
    );
}

// ============================================
// 12. CONNECTION CLOSE FUNCTION
// ============================================
function closeConnection() {
    global $conn;
    if ($conn) {
        mysqli_close($conn);
    }
}

// ============================================
// END OF CONFIG.PHP
// ============================================
?>