<?php
// app/Controllers/AdminController.php

class AdminController {
    private function requireAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
            header('Location: /restpo/login'); exit;
        }
    }

    public function updateProfile() {
        $this->requireAdmin();
        $db = getDB();

        $redirect = trim($_POST['redirect_url'] ?? '/restpo/admin/dashboard');
        $redirectBase = strtok($redirect, '?');
        if (empty($redirectBase)) {
            $redirectBase = '/restpo/admin/dashboard';
        }

        $name    = trim($_POST['name']            ?? '');
        $email   = trim($_POST['email']           ?? '');
        $phone   = trim($_POST['phone']           ?? '');
        $newPw   = $_POST['new_password']         ?? '';
        $confPw  = $_POST['confirm_password']     ?? '';

        if (!$name || !$email) {
            header('Location: ' . $redirectBase . '?profile_error=' . urlencode('Name and email are required'));
            exit;
        }

        // Email uniqueness (exclude self)
        $check = $db->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
        $check->execute([$email, $_SESSION['user_id']]);
        if ($check->fetch()) {
            header('Location: ' . $redirectBase . '?profile_error=' . urlencode('Email already in use'));
            exit;
        }

        if ($newPw) {
            if ($newPw !== $confPw) {
                header('Location: ' . $redirectBase . '?profile_error=' . urlencode('Passwords do not match'));
                exit;
            }
            if (strlen($newPw) < 6) {
                header('Location: ' . $redirectBase . '?profile_error=' . urlencode('Password must be at least 6 characters'));
                exit;
            }
            $hashed = password_hash($newPw, PASSWORD_BCRYPT);
            $db->prepare('UPDATE users SET name=?, email=?, phone=?, password=? WHERE id=?')
               ->execute([$name, $email, $phone, $hashed, $_SESSION['user_id']]);
        } else {
            $db->prepare('UPDATE users SET name=?, email=?, phone=? WHERE id=?')
               ->execute([$name, $email, $phone, $_SESSION['user_id']]);
        }

        // Sync session
        $_SESSION['name']  = $name;
        $_SESSION['email'] = $email;
        $_SESSION['phone'] = $phone;

        header('Location: ' . $redirectBase . '?msg=' . urlencode('Profile updated successfully'));
        exit;
    }

    public function settings() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Settings';

        // Get restaurant details (name, phone, address, logo)
        $rStmt = $db->prepare('SELECT * FROM restaurants WHERE id = ?');
        $rStmt->execute([$rest_id]);
        $restaurant = $rStmt->fetch();

        // Get current settings
        $stmt = $db->prepare('SELECT setting_key, setting_value FROM restaurant_settings WHERE restaurant_id = ?');
        $stmt->execute([$rest_id]);
        $rows = $stmt->fetchAll();
        $settings = [];
        foreach ($rows as $r) { $settings[$r['setting_key']] = $r['setting_value']; }

        $tax_rate = $settings['tax_rate'] ?? '5';
        $discount_rate = $settings['discount_rate'] ?? '0';

        ob_start();
        require 'app/Views/admin/settings/index.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function updateSettings() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];

        $name    = trim($_POST['name'] ?? '');
        $phone   = trim($_POST['phone'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $currency = trim($_POST['currency'] ?? '$');
        $slug = trim($_POST['slug'] ?? '');

        // Clean slug
        $slug = strtolower(preg_replace('/[^a-zA-Z0-9\-_]/', '', $slug));

        if (empty($name)) {
            header('Location: /restpo/admin/settings?error=' . urlencode('Restaurant name is required'));
            exit;
        }

        // Check slug uniqueness
        if (!empty($slug)) {
            $checkSlug = $db->prepare('SELECT id FROM restaurants WHERE slug = ? AND id != ?');
            $checkSlug->execute([$slug, $rest_id]);
            if ($checkSlug->fetch()) {
                header('Location: /restpo/admin/settings?error=' . urlencode('The custom URL slug is already taken. Please choose another one.'));
                exit;
            }
        } else {
            $slug = null;
        }

        // Handle file upload for logo (convert to WebP)
        $logo_path = null;
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            try {
                require_once 'app/Helpers/ImageUploader.php';
                $logo_path = ImageUploader::saveLogoImage($_FILES['logo'], (int)$rest_id);
            } catch (\Exception $e) {
                header('Location: /restpo/admin/settings?error=' . urlencode('Logo upload failed: ' . $e->getMessage()));
                exit;
            }
        }

        // Update restaurants table
        if ($logo_path) {
            $db->prepare('UPDATE restaurants SET name = ?, phone = ?, address = ?, logo = ?, slug = ?, currency = ? WHERE id = ?')
               ->execute([$name, $phone, $address, $logo_path, $slug, $currency, $rest_id]);
        } else {
            $db->prepare('UPDATE restaurants SET name = ?, phone = ?, address = ?, slug = ?, currency = ? WHERE id = ?')
               ->execute([$name, $phone, $address, $slug, $currency, $rest_id]);
        }

        // Update session currency and sync user table currency
        $_SESSION['currency'] = $currency;
        $db->prepare('UPDATE users SET currency = ? WHERE id = ?')
           ->execute([$currency, $_SESSION['user_id']]);

        $tax_rate = max(0, min(100, floatval($_POST['tax_rate'] ?? 5)));
        $discount_rate = max(0, min(100, floatval($_POST['discount_rate'] ?? 0)));

        $order_id_flow = $_POST['order_id_flow'] ?? 'global';
        $thermal_printing_size = $_POST['thermal_printing_size'] ?? '80mm';
        $print_popup_kot = $_POST['print_popup_kot'] ?? 'silent';
        $print_popup_bill = $_POST['print_popup_bill'] ?? 'silent';
        $print_popup_receipt = $_POST['print_popup_receipt'] ?? 'silent';

        // Upsert tax_rate
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "tax_rate", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $tax_rate, $tax_rate]);

        // Upsert discount_rate
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "discount_rate", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $discount_rate, $discount_rate]);

        // Upsert order_id_flow
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "order_id_flow", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $order_id_flow, $order_id_flow]);

        // Upsert thermal_printing_size
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "thermal_printing_size", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $thermal_printing_size, $thermal_printing_size]);

        // Upsert print_popup_kot
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "print_popup_kot", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $print_popup_kot, $print_popup_kot]);

        // Upsert print_popup_bill
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "print_popup_bill", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $print_popup_bill, $print_popup_bill]);

        // Upsert print_popup_receipt
        $db->prepare('INSERT INTO restaurant_settings (restaurant_id, setting_key, setting_value) VALUES (?, "print_popup_receipt", ?) ON DUPLICATE KEY UPDATE setting_value = ?')
           ->execute([$rest_id, $print_popup_receipt, $print_popup_receipt]);



        header('Location: /restpo/admin/settings?msg=Settings+updated+successfully');
        exit;
    }

    public function checkSlug() {
        $this->requireAdmin();
        header('Content-Type: application/json');
        
        $data = json_decode(file_get_contents('php://input'), true);
        $slug = trim($data['slug'] ?? '');
        $rest_id = $_SESSION['restaurant_id'];

        // Clean slug
        $slug = strtolower(preg_replace('/[^a-zA-Z0-9\-_]/', '', $slug));

        if (empty($slug)) {
            echo json_encode(['available' => true, 'slug' => '']);
            exit;
        }

        $db = getDB();
        $stmt = $db->prepare('SELECT id FROM restaurants WHERE slug = ? AND id != ?');
        $stmt->execute([$slug, $rest_id]);
        $exists = $stmt->fetch();

        echo json_encode(['available' => !$exists, 'slug' => $slug]);
        exit;
    }

    // ── Customer Feedback Review ───────────────────────
    public function feedback() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Customer Feedback';

        // Get active floors for filtering
        $floors = $db->prepare('SELECT * FROM floors WHERE restaurant_id = ? ORDER BY name');
        $floors->execute([$rest_id]);
        $floors = $floors->fetchAll();

        // Get filters from query string
        $floor_filter = !empty($_GET['floor_id']) ? intval($_GET['floor_id']) : null;
        $type_filter = !empty($_GET['type']) ? $_GET['type'] : null;

        $sql = '
            SELECT fb.*, f.name as floor_name, t.name as table_name 
            FROM feedbacks fb 
            LEFT JOIN floors f ON f.id = fb.floor_id 
            LEFT JOIN tables t ON t.id = fb.table_id 
            WHERE fb.restaurant_id = ?
        ';
        $params = [$rest_id];

        if ($floor_filter) {
            $sql .= ' AND fb.floor_id = ?';
            $params[] = $floor_filter;
        }

        if ($type_filter) {
            $sql .= ' AND fb.type = ?';
            $params[] = $type_filter;
        }

        $sql .= ' ORDER BY fb.id DESC';

        $feedbackStmt = $db->prepare($sql);
        $feedbackStmt->execute($params);
        $feedbacks = $feedbackStmt->fetchAll();

        ob_start();
        require 'app/Views/admin/feedback/index.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function deleteFeedback() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $id = intval($_POST['id'] ?? 0);

        if ($id) {
            $db->prepare('DELETE FROM feedbacks WHERE id = ? AND restaurant_id = ?')
               ->execute([$id, $rest_id]);
            header('Location: /restpo/admin/feedback?msg=Feedback+deleted+successfully');
        } else {
            header('Location: /restpo/admin/feedback?error=Invalid+feedback+ID');
        }
        exit;
    }
}
