<?php
// app/Controllers/HomeController.php
// Handles: Landing page, Registration, Contact form

class HomeController {

    /**
     * Landing page - the public-facing homepage
     */
    public function landing() {
        // If user is already logged in, redirect to their dashboard
        if (isset($_SESSION['user_id'])) {
            $role = $_SESSION['role'];
            $map = [
                'superadmin' => '/superadmin/dashboard',
                'admin'      => '/admin/dashboard',
                'cashier'    => '/pos',
                'waiter'     => '/waiter',
                'kitchen'    => '/kitchen',
                'inventory'  => '/inventory',
                'hr_manager' => '/hr',
            ];
            header('Location: ' . ($map[$role] ?? '/login'));
            exit;
        }

        $db = getDB();

        // Fetch active packages grouped by currency
        $packages = $db->query('SELECT * FROM packages WHERE status="active" ORDER BY price ASC')->fetchAll();
        $usdPackages = [];
        $bdtPackages = [];
        foreach ($packages as $pkg) {
            $pkg['features_decoded'] = json_decode($pkg['features'] ?? '{}', true) ?: [];
            if (($pkg['currency'] ?? '$') === '৳') {
                $bdtPackages[] = $pkg;
            } else {
                $usdPackages[] = $pkg;
            }
        }

        // Fetch video reviews
        $reviews = $db->query('SELECT * FROM video_reviews ORDER BY created_at DESC')->fetchAll();

        // Fetch site settings for hero video URL, contact info, etc.
        $siteSettings = [];
        try {
            $rows = $db->query('SELECT * FROM site_settings')->fetchAll();
            foreach ($rows as $row) {
                $siteSettings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Exception $e) {
            // Table might not exist
        }

        $heroVideoUrl = $siteSettings['hero_video_url'] ?? 'https://www.youtube.com/embed/dQw4w9WgXcQ';
        $featureVideoUrl = $siteSettings['feature_video_url'] ?? $heroVideoUrl;
        $contactEmail = $siteSettings['contact_email'] ?? 'info@restpo.com';
        $contactPhone = $siteSettings['contact_phone'] ?? '+1 234 567 890';
        $contactAddress = $siteSettings['contact_address'] ?? '';

        // Overwrite contact email and phone with super admin (id=1) details if edited
        try {
            $superAdmin = $db->query('SELECT email, phone FROM users WHERE id = 1 LIMIT 1')->fetch();
            if ($superAdmin) {
                if (!empty($superAdmin['email'])) {
                    $contactEmail = $superAdmin['email'];
                }
                if (!empty($superAdmin['phone'])) {
                    $contactPhone = $superAdmin['phone'];
                }
            }
        } catch (\Exception $e) {
            // Fallback
        }

        require 'app/Views/home/landing.php';
    }

    /**
     * Registration form page
     */
    public function register() {
        if (isset($_SESSION['user_id'])) {
            header('Location: /dashboard');
            exit;
        }

        $db = getDB();
        $packages = $db->query('SELECT * FROM packages WHERE status="active" ORDER BY price ASC')->fetchAll();

        // Fetch site settings for website logo
        $websiteLogo = null;
        try {
            $websiteLogo = $db->query('SELECT setting_value FROM site_settings WHERE setting_key="website_logo"')->fetchColumn();
        } catch (\Exception $e) {}

        $error = $_GET['error'] ?? null;
        $success = $_GET['success'] ?? null;

        require 'app/Views/home/register.php';
    }

    /**
     * Handle registration form submission
     */
    public function submitRegister() {
        $db = getDB();

        $restaurantName = trim($_POST['restaurant_name'] ?? '');
        $restaurantEmail = trim($_POST['restaurant_email'] ?? '');
        $restaurantPhone = trim($_POST['restaurant_phone'] ?? '');
        $restaurantAddress = trim($_POST['restaurant_address'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $adminName = trim($_POST['admin_name'] ?? '');
        $adminEmail = trim($_POST['admin_email'] ?? '');
        $adminPassword = $_POST['admin_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        $packageId = $_POST['package_id'] ?? null;
        $message = trim($_POST['message'] ?? '');

        // Validation
        if (!$restaurantName || !$adminName || !$adminEmail || !$adminPassword) {
            header('Location: /register?error=' . urlencode('Restaurant name, admin name, email, and password are required.')); exit;
        }

        if ($adminPassword !== $confirmPassword) {
            header('Location: /register?error=' . urlencode('Passwords do not match.')); exit;
        }

        if (strlen($adminPassword) < 6) {
            header('Location: /register?error=' . urlencode('Password must be at least 6 characters.')); exit;
        }

        // Generate unique slug automatically
        $baseSlug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $restaurantName));
        $baseSlug = trim($baseSlug, '-');
        if (empty($baseSlug)) {
            $baseSlug = 'restaurant';
        }
        
        $slug = $baseSlug;
        $counter = 1;
        while (true) {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE slug = ?');
            $stmt->execute([$slug]);
            if ($stmt->fetchColumn() == 0) {
                break;
            }
            $slug = $baseSlug . '-' . $counter;
            $counter++;
        }

        // Check restaurant email uniqueness
        if ($restaurantEmail !== '') {
            $stmt = $db->prepare('SELECT COUNT(*) FROM restaurants WHERE email = ?');
            $stmt->execute([$restaurantEmail]);
            if ($stmt->fetchColumn() > 0) {
                header('Location: /register?error=' . urlencode('Restaurant email address is already in use.')); exit;
            }
        }

        // Check admin email uniqueness
        $stmt = $db->prepare('SELECT COUNT(*) FROM users WHERE email = ?');
        $stmt->execute([$adminEmail]);
        if ($stmt->fetchColumn() > 0) {
            header('Location: /register?error=' . urlencode('Admin email address is already in use.')); exit;
        }

        $db->beginTransaction();
        try {
            // Create restaurant with pending approval
            $stmt = $db->prepare('INSERT INTO restaurants (name, slug, email, phone, address, status, approval_status, admin_notes, package_id) VALUES (?, ?, ?, ?, ?, "inactive", "pending", ?, ?)');
            $stmt->execute([$restaurantName, $slug, $restaurantEmail ?: null, $restaurantPhone ?: null, $restaurantAddress ?: null, $message ?: null, $packageId ?: null]);
            $restaurantId = $db->lastInsertId();

            // Create admin user with inactive status
            $hashedPassword = password_hash($adminPassword, PASSWORD_BCRYPT);
            $stmt = $db->prepare('INSERT INTO users (restaurant_id, name, email, password, role, phone, status) VALUES (?, ?, ?, ?, "admin", ?, "inactive")');
            $stmt->execute([$restaurantId, $adminName, $adminEmail, $hashedPassword, $restaurantPhone ?: null]);

            // Also save in package_requests for tracking
            $preferredFeatures = json_encode(['package_id' => $packageId, 'slug' => $slug]);
            $stmt = $db->prepare('INSERT INTO package_requests (name, email, phone, restaurant_name, message, preferred_features, status) VALUES (?, ?, ?, ?, ?, ?, "pending")');
            $stmt->execute([$adminName, $adminEmail, $restaurantPhone ?: null, $restaurantName, $message ?: 'New registration', $preferredFeatures]);

            $db->commit();
            header('Location: /register/pending'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /register?error=' . urlencode('Registration failed: ' . $e->getMessage())); exit;
        }
    }

    /**
     * Show pending registration confirmation page
     */
    public function pending() {
        $websiteLogo = null;
        try {
            $websiteLogo = getDB()->query('SELECT setting_value FROM site_settings WHERE setting_key="website_logo"')->fetchColumn();
        } catch (\Exception $e) {}
        require 'app/Views/home/pending.php';
    }

    /**
     * Handle contact form submission (AJAX)
     */
    public function submitContact() {
        header('Content-Type: application/json');

        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $subject = trim($_POST['subject'] ?? '');
        $message = trim($_POST['message'] ?? '');

        if (!$name || !$email || !$subject || !$message) {
            echo json_encode(['success' => false, 'message' => 'Please fill in all required fields.']);
            exit;
        }

        try {
            $db = getDB();
            $stmt = $db->prepare('INSERT INTO contact_messages (name, email, phone, subject, message) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([$name, $email, $phone ?: null, $subject, $message]);

            echo json_encode(['success' => true, 'message' => 'Thank you! Your message has been sent. We will get back to you soon.']);
        } catch (\Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Failed to send message. Please try again.']);
        }
        exit;
    }
}
