<?php

namespace App\Controllers;

use App\Core\Controller;
use MailService;

class ContactController extends Controller {
    
    public function index() {
        $this->view('contact', [
            'title' => __('contact_us') . ' - ' . get_setting('site_name', 'ApkNusa')
        ]);
    }

    public function submit() {
        $name = $_POST['name'] ?? '';
        $email = $_POST['email'] ?? '';
        $subject = $_POST['subject'] ?? 'New Contact Message';
        $message = $_POST['message'] ?? '';

        if (empty($name) || empty($email) || empty($message)) {
            $_SESSION['error'] = 'All fields are required.';
            $this->redirect('/contact');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $_SESSION['error'] = 'Invalid email address.';
            $this->redirect('/contact');
        }

        require_once __DIR__ . '/../../mail/MailService.php';
        
        $res = \MailService::sendContactMessage($name, $email, $message, null, $subject);

        if (!empty($res['success'])) {
            $_SESSION['success'] = 'Your message has been sent successfully!';
        } else {
            $_SESSION['error'] = 'Failed to send message. Please try again later.';
        }

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

    public function ajaxReport() {
        if (!is_ajax()) {
            $this->redirect('/');
        }

        header('Content-Type: application/json');

        $email = $_POST['email'] ?? '';
        $subject = $_POST['subject'] ?? 'App Report';
        $message = $_POST['message'] ?? '';
        $apk_name = $_POST['apk_name'] ?? 'Unknown App';

        if (empty($email) || empty($message)) {
            echo json_encode(['error' => 'Email and message are required.']);
            exit;
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(['error' => 'Invalid email address.']);
            exit;
        }

        require_once __DIR__ . '/../../mail/MailService.php';
        
        $full_message = "Report for App: $apk_name\n\nUser Email: $email\n\nMessage:\n$message";
        $res = \MailService::sendContactMessage('System Report', $email, $full_message, null, $subject);

        if (!empty($res['success'])) {
            echo json_encode(['success' => 'Report submitted successfully!']);
        } else {
            echo json_encode(['error' => 'Failed to submit report.']);
        }
        exit;
    }
}