<?php
// controllers/HomeController.php
// Home page controller

require_once 'BaseController.php';
require_once 'models/Service.php';
require_once 'models/GalleryImage.php';
require_once 'models/GalleryCategory.php';
require_once 'models/Testimonial.php';
require_once 'models/Page.php';

class HomeController extends BaseController {
    
    public function index() {
        // Load models
        $serviceModel = new Service();
        $galleryModel = new GalleryImage();
        $testimonialModel = new Testimonial();
        $pageModel = new Page();

        // Get data
        $services = $serviceModel->getFeatured(6);
        $featuredImages = $galleryModel->getFeatured(8);
        if (empty($featuredImages)) {
            $featuredImages = $galleryModel->getRecentActive(8);
        }
        $testimonials = $testimonialModel->getFeatured(3);
        
        // Get about page content
        $aboutPage = $pageModel->getBySlug('hakkimizda');

        $this->render('home/index', [
            'services' => $services,
            'featuredImages' => $featuredImages,
            'testimonials' => $testimonials,
            'aboutPage' => $aboutPage
        ]);
    }

    public function about() {
        $pageModel = new Page();
        $page = $pageModel->getBySlug('hakkimizda');
        
        if (!$page) {
            $this->redirect('/404');
        }

        $this->render('pages/about', [
            'page' => $page
        ]);
    }

    public function services() {
        $serviceModel = new Service();
        $services = $serviceModel->getAllActive();

        $this->render('pages/services', [
            'services' => $services
        ]);
    }

    public function gallery() {
        $galleryModel = new GalleryImage();
        $categoryModel = new GalleryCategory();
        
        $images = $galleryModel->getAllWithCategory();
        $categories = $categoryModel->getWithImageCount();

        $this->render('pages/gallery', [
            'images' => $images,
            'categories' => $categories
        ]);
    }

    public function contact() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleContactForm();
            return;
        }

        $this->render('pages/contact');
    }

    public function page($slug) {
        $pageModel = new Page();
        $page = $pageModel->getBySlug($slug);
        
        if (!$page) {
            http_response_code(404);
            echo '<!DOCTYPE html>
            <html lang="tr">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>404 - Sayfa Bulunamadı</title>
                <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
            </head>
            <body class="bg-light">
                <div class="container">
                    <div class="row justify-content-center">
                        <div class="col-md-6 text-center">
                            <div class="mt-5">
                                <h1 class="display-1 text-primary">404</h1>
                                <h2 class="mb-4">Sayfa Bulunamadı</h2>
                                <p class="lead mb-4">Aradığınız sayfa mevcut değil veya taşınmış olabilir.</p>
                                <a href="/" class="btn btn-primary">Ana Sayfaya Dön</a>
                            </div>
                        </div>
                    </div>
                </div>
            </body>
            </html>';
            return;
        }

        $this->render('pages/dynamic', [
            'page' => $page
        ]);
    }

    private function handleContactForm() {
        $data = $this->sanitizeInput($this->getPostData());
        
        $requiredFields = ['name', 'email', 'message'];
        $errors = $this->validateRequired($data, $requiredFields);

        if (!empty($errors)) {
            setFlashMessage('error', implode('<br>', $errors));
            $this->redirect('/contact');
        }

        // Validate email
        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            setFlashMessage('error', 'Geçerli bir email adresi giriniz.');
            $this->redirect('/contact');
        }

        // Save contact message
        require_once 'models/ContactMessage.php';
        $contactModel = new ContactMessage();
        
        $messageData = [
            'name' => $data['name'],
            'email' => $data['email'],
            'phone' => $data['phone'] ?? '',
            'subject' => $data['subject'] ?? '',
            'message' => $data['message']
        ];

        if ($contactModel->create($messageData)) {
            // Send notification email to admin
            $this->sendContactNotification($messageData);
            
            setFlashMessage('success', 'Mesajınız başarıyla gönderildi. En kısa sürede size dönüş yapacağız.');
        } else {
            setFlashMessage('error', 'Mesaj gönderilirken bir hata oluştu. Lütfen tekrar deneyiniz.');
        }

        $this->redirect('/contact');
    }

    private function sendContactNotification($data) {
        $subject = 'Yeni İletişim Mesajı - ' . SITE_NAME;
        $message = "
        <h2>Yeni İletişim Mesajı</h2>
        <p><strong>Ad Soyad:</strong> {$data['name']}</p>
        <p><strong>Email:</strong> {$data['email']}</p>
        <p><strong>Telefon:</strong> {$data['phone']}</p>
        <p><strong>Konu:</strong> {$data['subject']}</p>
        <p><strong>Mesaj:</strong></p>
        <p>{$data['message']}</p>
        ";

        $adminEmail = $this->data['settings']['contact_email'] ?? FROM_EMAIL;
        sendEmail($adminEmail, $subject, $message);
    }
}
?>
