<?php

namespace App\Controllers;

use App\Models\ProductModel;

class ProductController extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();

        // Get filter inputs
        $search = $this->request->getVar('search');
        $category = $this->request->getVar('category');
        $minPrice = $this->request->getVar('min_price');
        $maxPrice = $this->request->getVar('max_price');
        $rating = $this->request->getVar('rating');
        $koperasiId = $this->request->getVar('koperasi_id');
        $sortBy = $this->request->getVar('sort_by'); // terlaris, terbaru, termurah, termahal

        // Build query
        $builder = $db->table('products p');
        $builder->select('p.*, k.nama_koperasi, k.logo as koperasi_logo, c.category_name, (SELECT IFNULL(SUM(qty), 0) FROM order_items WHERE product_id = p.id) as terjual');
        $builder->join('koperasi k', 'k.id = p.koperasi_id');
        $builder->join('categories c', 'c.id = p.kategori_id');

        if ($search) {
            $builder->groupStart()
                    ->like('p.nama_produk', $search)
                    ->orLike('p.tags', $search)
                    ->groupEnd();
        }

        if ($category) {
            $builder->where('p.kategori_id', $category);
        }

        if ($koperasiId) {
            $builder->where('p.koperasi_id', $koperasiId);
        }

        if ($minPrice) {
            $builder->where('p.harga >=', $minPrice);
        }

        if ($maxPrice) {
            $builder->where('p.harga <=', $maxPrice);
        }

        if ($rating) {
            $builder->where('p.rating >=', $rating);
        }

        // Apply Sorting
        if ($sortBy === 'terbaru') {
            $builder->orderBy('p.created_at', 'DESC');
        } else if ($sortBy === 'termurah') {
            $builder->orderBy('p.harga', 'ASC');
        } else if ($sortBy === 'termahal') {
            $builder->orderBy('p.harga', 'DESC');
        } else if ($sortBy === 'terlaris') {
            $builder->orderBy('p.rating', 'DESC');
        } else {
            $builder->orderBy('p.id', 'DESC');
        }

        $products = $builder->get()->getResultArray();

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $products
        ]);
    }

    public function show($id)
    {
        $db = \Config\Database::connect();
        $builder = $db->table('products p');
        $builder->select('p.*, k.nama_koperasi, k.logo as koperasi_logo, k.alamat as koperasi_alamat, c.category_name, (SELECT IFNULL(SUM(qty), 0) FROM order_items WHERE product_id = p.id) as terjual');
        $builder->join('koperasi k', 'k.id = p.koperasi_id');
        $builder->join('categories c', 'c.id = p.kategori_id');
        $builder->where('p.id', $id);
        
        $product = $builder->get()->getRowArray();

        if (!$product) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Produk tidak ditemukan'
            ])->setStatusCode(404);
        }

        // Mock similar products based on category
        $similar = $db->table('products')
            ->where('kategori_id', $product['kategori_id'])
            ->where('id !=', $product['id'])
            ->limit(4)
            ->get()
            ->getResultArray();

        // Mock customer reviews
        $reviews = [
            [
                'name' => 'Budi Santoso',
                'rating' => 5,
                'comment' => 'Kualitas produk sangat bagus! Sangat puas belanja di koperasi ini.',
                'date' => '2026-05-20'
            ],
            [
                'name' => 'Siti Aminah',
                'rating' => 4,
                'comment' => 'Pengiriman cepat, packing rapi, rasanya enak sekali.',
                'date' => '2026-05-18'
            ]
        ];

        return $this->response->setJSON([
            'status' => 'success',
            'data' => $product,
            'similar_products' => $similar,
            'reviews' => $reviews
        ]);
    }

    public function create()
    {
        $productModel = new ProductModel();

        $rules = [
            'koperasi_id' => 'required',
            'category_id' => 'required',
            'name' => 'required',
            'price' => 'required|numeric',
            'stock' => 'required|integer',
        ];

        if (!$this->validate($rules)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Validasi gagal',
                'errors' => $this->validator->getErrors()
            ])->setStatusCode(400);
        }

        // Auto-add column satuan to products table to prevent crash
        try {
            $db = \Config\Database::connect();
            $db->query("ALTER TABLE products ADD COLUMN satuan VARCHAR(50) DEFAULT 'unit'");
        } catch (\Exception $e) {}

        $data = [
            'koperasi_id' => $this->request->getVar('koperasi_id'),
            'kategori_id' => $this->request->getVar('category_id'),
            'nama_produk' => $this->request->getVar('name'),
            'harga' => $this->request->getVar('price'),
            'satuan' => $this->request->getVar('satuan') ?: 'unit',
            'stok' => $this->request->getVar('stock'),
            'deskripsi' => $this->request->getVar('description'),
            'foto' => $this->request->getVar('image') ?: 'https://images.unsplash.com/photo-1546069901-ba9599a7e63c?w=500', // default
            'rating' => 5.00,
            'tags' => $this->request->getVar('tags') ?: '',
            'status' => 'aktif',
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $productId = $productModel->insert($data);

        // Add log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Tambah Produk Baru',
            'notes' => 'Produk baru "' . $data['nama_produk'] . '" ditambahkan ke koperasi ID ' . $data['koperasi_id'],
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Produk berhasil ditambahkan',
            'product_id' => $productId
        ]);
    }

    public function recommendations()
    {
        $db = \Config\Database::connect();
        $interest = $this->request->getVar('interest') ?: '';

        $builder = $db->table('products p');
        $builder->select('p.*, k.nama_koperasi');
        $builder->join('koperasi k', 'k.id = p.koperasi_id');
        
        if ($interest) {
            $builder->like('p.tags', $interest);
        }
        
        $builder->limit(4);
        $products = $builder->get()->getResultArray();

        // If nothing matches, pull top-rated products
        if (empty($products)) {
            $products = $db->table('products p')
                ->select('p.*, k.nama_koperasi')
                ->join('koperasi k', 'k.id = p.koperasi_id')
                ->orderBy('p.rating', 'DESC')
                ->limit(4)
                ->get()
                ->getResultArray();
        }

        return $this->response->setJSON([
            'status' => 'success',
            'algorithm' => 'Collaborative Filtering + Content-Based AI',
            'interest_queried' => $interest,
            'data' => $products
        ]);
    }

    public function uploadImage()
    {
        $file = $this->request->getFile('image');
        if ($file && $file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            if (!is_dir(WRITEPATH . 'uploads/img')) {
                mkdir(WRITEPATH . 'uploads/img', 0777, true);
            }
            $file->move(WRITEPATH . 'uploads/img', $newName);
            return $this->response->setJSON([
                'status' => 'success',
                'url' => 'api/products/image/' . $newName
            ]);
        }
        $errorMsg = $file ? $file->getErrorString() : 'No file uploaded or invalid key';
        return $this->response->setJSON(['status' => 'error', 'message' => 'Upload failed: ' . $errorMsg]);
    }

    /**
     * POST /api/products/(:num)/update
     * Update product (CRUD - Edit)
     */
    public function updateProduct($id)
    {
        $db = \Config\Database::connect();

        $data = [];
        if ($this->request->getVar('name'))        $data['nama_produk'] = $this->request->getVar('name');
        if ($this->request->getVar('price'))       $data['harga']       = $this->request->getVar('price');
        if ($this->request->getVar('satuan'))      $data['satuan']      = $this->request->getVar('satuan');
        if ($this->request->getVar('stock') !== null) $data['stok']     = $this->request->getVar('stock');
        if ($this->request->getVar('description')) $data['deskripsi']   = $this->request->getVar('description');
        if ($this->request->getVar('category_id')) $data['kategori_id'] = $this->request->getVar('category_id');
        if ($this->request->getVar('image'))       $data['foto']        = $this->request->getVar('image');
        if ($this->request->getVar('tags'))        $data['tags']        = $this->request->getVar('tags');
        if ($this->request->getVar('status'))      $data['status']      = $this->request->getVar('status');

        if (empty($data)) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Tidak ada data untuk diperbarui'])->setStatusCode(400);
        }

        $db->table('products')->where('id', $id)->update($data);

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Produk berhasil diperbarui',
        ]);
    }

    /**
     * POST /api/products/(:num)/delete
     * Delete product (CRUD - Delete)
     */
    public function deleteProduct($id)
    {
        $db = \Config\Database::connect();

        $product = $db->table('products')->where('id', $id)->get()->getRowArray();
        if (!$product) {
            return $this->response->setJSON(['status' => 'error', 'message' => 'Produk tidak ditemukan'])->setStatusCode(404);
        }

        $db->table('products')->where('id', $id)->delete();

        // Log
        $db->table('audit_logs')->insert([
            'user_id'    => null,
            'action'     => 'Hapus Produk',
            'notes'      => 'Produk "' . $product['nama_produk'] . '" dihapus dari katalog.',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status'  => 'success',
            'message' => 'Produk berhasil dihapus',
        ]);
    }

    /**
     * GET /api/products/image/(:any)
     * Serve image from writable directory
     */
    public function serveImage($filename)
    {
        $path = WRITEPATH . 'uploads/img/' . $filename;
        if (!is_file($path)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        }

        $mime = mime_content_type($path);
        header('Content-Type: ' . $mime);
        header('Content-Length: ' . filesize($path));
        readfile($path);
        exit;
    }
}
