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

class LookupController {
    public function index() {
        $db = Database::getInstance();
        
        $tab = $_GET['tab'] ?? 'countries';
        
        if ($tab === 'countries') {
            $data = $db->query("SELECT * FROM countries ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'cities') {
            $data = $db->query("SELECT c.*, co.name_en as country_name FROM cities c LEFT JOIN countries co ON c.country_id = co.id ORDER BY c.name_en ASC")->fetchAll();
        } elseif ($tab === 'nationalities') {
            $data = $db->query("SELECT * FROM nationalities ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'languages') {
            $data = $db->query("SELECT * FROM languages ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'specialties') {
            $data = $db->query("SELECT * FROM specialties ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'skills') {
            $data = $db->query("SELECT * FROM skills ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'service_models') {
            $data = $db->query("SELECT * FROM service_models ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'accommodation_types') {
            $data = $db->query("SELECT * FROM accommodation_types ORDER BY name_en ASC")->fetchAll();
        } elseif ($tab === 'interview_platforms') {
            $data = $db->query("SELECT * FROM interview_platforms ORDER BY name ASC")->fetchAll();
        } elseif ($tab === 'document_types') {
            $data = $db->query("SELECT * FROM document_types ORDER BY name_en ASC")->fetchAll();
        } else {
            $data = [];
        }

        $countries = [];
        if ($tab === 'cities') {
            $countries = $db->query("SELECT id, name_en FROM countries ORDER BY name_en ASC")->fetchAll();
        }

        require __DIR__ . '/../../../../views/admin/lookups/index.php';
    }

    public function store() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
        
        $db = Database::getInstance();
        $tab = $_POST['tab'] ?? 'countries';
        $name_en = $_POST['name_en'] ?? '';
        $name_ar = $_POST['name_ar'] ?? '';
        
        if (empty($name_en)) {
            header("Location: ?page=lookups&tab=$tab&error=Name is required");
            exit;
        }

        // Different tables might have different columns
        if ($tab === 'interview_platforms') {
            $stmt = $db->prepare("INSERT INTO interview_platforms (name, status) VALUES (?, 'active')");
            $stmt->execute([$name_en]);
        } elseif ($tab === 'cities') {
            $country_id = $_POST['country_id'] ?? 0;
            $stmt = $db->prepare("INSERT INTO cities (country_id, name_en, name_ar, status) VALUES (?, ?, ?, 'active')");
            $stmt->execute([$country_id, $name_en, $name_ar]);
        } else {
            $stmt = $db->prepare("INSERT INTO $tab (name_en, name_ar, status) VALUES (?, ?, 'active')");
            $stmt->execute([$name_en, $name_ar]);
        }

        header("Location: ?page=lookups&tab=$tab&success=Item added");
        exit;
    }

    public function delete() {
        $db = Database::getInstance();
        $tab = $_GET['tab'] ?? 'countries';
        $id = $_GET['id'] ?? 0;
        
        if ($id) {
            $isUsed = false;
            
            if ($tab === 'countries') {
                $stmt1 = $db->prepare("SELECT COUNT(*) FROM maids WHERE country_id = ?"); $stmt1->execute([$id]);
                $stmt2 = $db->prepare("SELECT COUNT(*) FROM vendors WHERE country_id = ?"); $stmt2->execute([$id]);
                $stmt3 = $db->prepare("SELECT COUNT(*) FROM customers WHERE country_id = ?"); $stmt3->execute([$id]);
                $stmt4 = $db->prepare("SELECT COUNT(*) FROM cities WHERE country_id = ?"); $stmt4->execute([$id]);
                if ($stmt1->fetchColumn() > 0 || $stmt2->fetchColumn() > 0 || $stmt3->fetchColumn() > 0 || $stmt4->fetchColumn() > 0) {
                    $isUsed = true;
                }
            } elseif ($tab === 'cities') {
                $stmt1 = $db->prepare("SELECT COUNT(*) FROM maids WHERE city_id = ?"); $stmt1->execute([$id]);
                $stmt2 = $db->prepare("SELECT COUNT(*) FROM vendors WHERE city_id = ?"); $stmt2->execute([$id]);
                $stmt3 = $db->prepare("SELECT COUNT(*) FROM customers WHERE city_id = ?"); $stmt3->execute([$id]);
                if ($stmt1->fetchColumn() > 0 || $stmt2->fetchColumn() > 0 || $stmt3->fetchColumn() > 0) {
                    $isUsed = true;
                }
            } elseif ($tab === 'nationalities') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maids WHERE nationality_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'languages') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maid_languages WHERE language_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'specialties') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maid_specialties WHERE specialty_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'skills') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maid_skills WHERE skill_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'service_models') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maids WHERE service_model_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'accommodation_types') {
                $stmt = $db->prepare("SELECT COUNT(*) FROM maids WHERE accommodation_type_id = ?");
                $stmt->execute([$id]);
                if ($stmt->fetchColumn() > 0) $isUsed = true;
            } elseif ($tab === 'document_types') {
                $stmt1 = $db->prepare("SELECT COUNT(*) FROM maid_documents WHERE document_type_id = ?"); $stmt1->execute([$id]);
                $stmt2 = $db->prepare("SELECT COUNT(*) FROM vendor_documents WHERE document_type_id = ?"); $stmt2->execute([$id]);
                if ($stmt1->fetchColumn() > 0 || $stmt2->fetchColumn() > 0) {
                    $isUsed = true;
                }
            }
            
            if ($isUsed) {
                header("Location: ?page=lookups&tab=$tab&error=Cannot delete this item because it is actively assigned to maids, vendors, customers, or document templates. Try deactivating it instead!");
                exit;
            }
            
            $stmt = $db->prepare("DELETE FROM $tab WHERE id = ?");
            $stmt->execute([$id]);
        }
        
        header("Location: ?page=lookups&tab=$tab&success=Item deleted");
        exit;
    }

    public function update() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') return;
        
        $db = Database::getInstance();
        $tab = $_POST['tab'] ?? 'countries';
        $id = $_POST['id'] ?? 0;
        $name_en = $_POST['name_en'] ?? '';
        $name_ar = $_POST['name_ar'] ?? '';
        $status = $_POST['status'] ?? 'active';
        
        if (empty($name_en)) {
            header("Location: ?page=lookups&tab=$tab&error=Name is required");
            exit;
        }

        if ($tab === 'interview_platforms') {
            $stmt = $db->prepare("UPDATE interview_platforms SET name = ?, status = ? WHERE id = ?");
            $stmt->execute([$name_en, $status, $id]);
        } elseif ($tab === 'cities') {
            $country_id = $_POST['country_id'] ?? 0;
            $stmt = $db->prepare("UPDATE cities SET country_id = ?, name_en = ?, name_ar = ?, status = ? WHERE id = ?");
            $stmt->execute([$country_id, $name_en, $name_ar, $status, $id]);
        } else {
            $stmt = $db->prepare("UPDATE $tab SET name_en = ?, name_ar = ?, status = ? WHERE id = ?");
            $stmt->execute([$name_en, $name_ar, $status, $id]);
        }

        header("Location: ?page=lookups&tab=$tab&success=Item updated successfully");
        exit;
    }

    public function toggleStatus() {
        $db = Database::getInstance();
        $tab = $_GET['tab'] ?? 'countries';
        $id = $_GET['id'] ?? 0;
        $status = $_GET['status'] ?? 'active';
        
        if ($id) {
            $stmt = $db->prepare("UPDATE $tab SET status = ? WHERE id = ?");
            $stmt->execute([$status, $id]);
            header("Location: ?page=lookups&tab=$tab&success=Item status updated successfully");
        } else {
            header("Location: ?page=lookups&tab=$tab&error=Invalid Item ID");
        }
        exit;
    }
}
