<?php
require_once __DIR__ . '/../../../Middleware/AuthMiddleware.php';
require_once __DIR__ . '/../../../Models/Database.php';

class NotificationSettingController {
    public function get() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $db = Database::getInstance();

        // 1. Fetch current settings
        $stmt = $db->prepare("SELECT * FROM customer_notification_settings WHERE customer_id = ?");
        $stmt->execute([$customerId]);
        $settings = $stmt->fetch();

        // 2. If not found, insert and return defaults
        if (!$settings) {
            $stmt = $db->prepare("
                INSERT INTO customer_notification_settings (customer_id, enable_push, booking_updates, messages, account_activity) 
                VALUES (?, 1, 1, 1, 1)
            ");
            $stmt->execute([$customerId]);

            $settings = [
                'customer_id' => $customerId,
                'enable_push' => 1,
                'booking_updates' => 1,
                'messages' => 1,
                'account_activity' => 1
            ];
        }

        // 3. Format response with standard boolean cast
        $formatted = [
            'enable_push' => (bool)$settings['enable_push'],
            'booking_updates' => (bool)$settings['booking_updates'],
            'messages' => (bool)$settings['messages'],
            'account_activity' => (bool)$settings['account_activity']
        ];

        sendResponse($formatted, 'Notification settings loaded successfully');
    }

    public function update() {
        $payload = AuthMiddleware::authenticate('customer');
        $customerId = $payload['id'];

        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) $data = $_POST;

        $db = Database::getInstance();

        // 1. Fetch current settings as baseline
        $stmt = $db->prepare("SELECT * FROM customer_notification_settings WHERE customer_id = ?");
        $stmt->execute([$customerId]);
        $current = $stmt->fetch();

        // Fallback to defaults if no record exists
        if (!$current) {
            $current = [
                'enable_push' => 1,
                'booking_updates' => 1,
                'messages' => 1,
                'account_activity' => 1
            ];
        }

        // 2. Filter and merge new toggle inputs (accept boolean or 0/1 integers)
        $enablePush = isset($data['enable_push']) ? ($data['enable_push'] ? 1 : 0) : (int)$current['enable_push'];
        $bookingUpdates = isset($data['booking_updates']) ? ($data['booking_updates'] ? 1 : 0) : (int)$current['booking_updates'];
        $messages = isset($data['messages']) ? ($data['messages'] ? 1 : 0) : (int)$current['messages'];
        $accountActivity = isset($data['account_activity']) ? ($data['account_activity'] ? 1 : 0) : (int)$current['account_activity'];

        // 3. Perform Upsert operation
        $stmt = $db->prepare("
            INSERT INTO customer_notification_settings (customer_id, enable_push, booking_updates, messages, account_activity, updated_at)
            VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
            ON DUPLICATE KEY UPDATE 
                enable_push = VALUES(enable_push),
                booking_updates = VALUES(booking_updates),
                messages = VALUES(messages),
                account_activity = VALUES(account_activity),
                updated_at = CURRENT_TIMESTAMP
        ");
        $stmt->execute([$customerId, $enablePush, $bookingUpdates, $messages, $accountActivity]);

        // 4. Format and return updated settings
        $formatted = [
            'enable_push' => (bool)$enablePush,
            'booking_updates' => (bool)$bookingUpdates,
            'messages' => (bool)$messages,
            'account_activity' => (bool)$accountActivity
        ];

        sendResponse($formatted, 'Notification settings updated successfully');
    }
}
