<?php

namespace App\Controllers\Admin;

use App\Models\EnquiryModel;

class Enquiries extends AdminBaseController
{
    public function index()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new EnquiryModel();
        $data['enquiries'] = $model->orderBy('created_at', 'DESC')->findAll();
        $data['title'] = 'Manage Enquiries';

        return view('admin/enquiries/index', $data);
    }

    public function view($id)
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new EnquiryModel();
        $enquiry = $model->find($id);

        if (!$enquiry) {
            $this->session->setFlashdata('error', 'Enquiry not found.');
            return redirect()->to('/admin/enquiries');
        }

        if ($enquiry['status'] == 'new') {
            $model->update($id, ['status' => 'read']);
            $enquiry['status'] = 'read';
        }

        $data['enquiry'] = $enquiry;
        
        $data['product'] = null;
        if (!empty($enquiry['product_id'])) {
            $productModel = new \App\Models\ProductModel();
            $data['product'] = $productModel->find($enquiry['product_id']);
        }

        $data['title'] = 'View Enquiry';
        return view('admin/enquiries/view', $data);
    }

    public function status($id, $status)
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new EnquiryModel();
        $validStatuses = ['new', 'read', 'replied'];
        
        if (in_array($status, $validStatuses)) {
            $model->update($id, ['status' => $status]);
            $this->session->setFlashdata('success', 'Status updated successfully.');
        } else {
            $this->session->setFlashdata('error', 'Invalid status.');
        }
        
        return redirect()->to('/admin/enquiries');
    }

    public function export()
    {
        if (!$this->checkAuth()) return redirect()->to('/admin/login');

        $model = new EnquiryModel();
        $enquiries = $model->orderBy('created_at', 'DESC')->findAll();

        $filename = 'enquiries_' . date('Ymd') . '.csv';
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-Type: application/csv; ");

        $file = fopen('php://output', 'w');
        $header = array("ID", "Type", "Name", "Email", "Phone", "Message", "Status", "Date");
        fputcsv($file, $header);
        foreach ($enquiries as $line){
            fputcsv($file, [
                $line['id'],
                $line['type'],
                $line['name'],
                $line['email'],
                $line['phone'],
                $line['message'],
                $line['status'],
                $line['created_at']
            ]);
        }
        fclose($file);
        exit;
    }
}
