<?php

namespace App\Controllers;

use App\Models\KoperasiModel;

class CooperativeController extends BaseController
{
    public function index()
    {
        $koperasiModel = new KoperasiModel();
        $status = $this->request->getVar('status');
        $kabupaten = $this->request->getVar('kabupaten');

        $query = $koperasiModel;
        if ($status) {
            $query = $query->where('status', $status);
        }
        if ($kabupaten) {
            $query = $query->where('kabupaten', $kabupaten);
        }

        $data = $query->orderBy('id', 'DESC')->findAll();

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

    public function stats()
    {
        $db = \Config\Database::connect();

        // 1. Cooperative stats
        $totalCoops = $db->table('koperasi')->countAllResults();
        $activeCoops = $db->table('koperasi')->where('status', 'aktif')->countAllResults();
        $pendingCoops = $db->table('koperasi')->where('status', 'pending')->countAllResults();

        // 2. User stats
        $totalUsers = $db->table('users')->countAllResults();
        $totalCustomers = $db->table('users')->where('role_id', 4)->countAllResults();

        // 3. Product stats
        $totalProducts = $db->table('products')->countAllResults();

        // 4. Sales stats
        $totalOrders = $db->table('orders')->countAllResults();
        $totalRevenue = $db->table('orders')
            ->whereIn('status', ['COMPLETED', 'PAYMENT_VERIFIED', 'WAITING_PROCESS', 'VERIFIKASI_KOPERASI', 'PACKING', 'READY_TO_SHIP', 'SHIPPED', 'IN_TRANSIT', 'ARRIVED_DESTINATION', 'OUT_FOR_DELIVERY', 'DELIVERED', 'completed', 'paid', 'processing', 'shipped'])
            ->selectSum('total')
            ->get()
            ->getRowArray()['total'] ?: 0;

        // 5. Regional breakdown
        $regions = $db->table('koperasi')
            ->select('kabupaten, COUNT(id) as count')
            ->groupBy('kabupaten')
            ->get()
            ->getResultArray();

        // 6. Recent sales charts mock
        $salesTimeline = [
            ['date' => '24 Mei', 'sales' => 1500000],
            ['date' => '25 Mei', 'sales' => 2400000],
            ['date' => '26 Mei', 'sales' => 1800000],
            ['date' => '27 Mei', 'sales' => 3200000],
            ['date' => '28 Mei', 'sales' => 4500000],
            ['date' => '29 Mei', 'sales' => 5100000],
        ];

        return $this->response->setJSON([
            'status' => 'success',
            'data' => [
                'total_cooperatives' => $totalCoops,
                'active_cooperatives' => $activeCoops,
                'pending_cooperatives' => $pendingCoops,
                'total_users' => $totalUsers,
                'total_customers' => $totalCustomers,
                'total_products' => $totalProducts,
                'total_orders' => $totalOrders,
                'total_revenue' => $totalRevenue,
                'regions' => $regions,
                'sales_timeline' => $salesTimeline
            ]
        ]);
    }

    public function create()
    {
        $koperasiModel = new KoperasiModel();

        $rules = [
            'kode_koperasi' => 'required|is_unique[koperasi.kode_koperasi]',
            'nama_koperasi' => 'required',
            'alamat' => 'required',
            'kabupaten' => 'required',
            'provinsi' => 'required',
        ];

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

        $data = [
            'kode_koperasi' => $this->request->getVar('kode_koperasi'),
            'nama_koperasi' => $this->request->getVar('nama_koperasi'),
            'alamat' => $this->request->getVar('alamat'),
            'kabupaten' => $this->request->getVar('kabupaten'),
            'provinsi' => $this->request->getVar('provinsi'),
            'logo' => $this->request->getVar('logo') ?: 'https://images.unsplash.com/photo-1543269865-cbf427effbad?w=150',
            'status' => 'pending',
            'created_at' => date('Y-m-d H:i:s'),
        ];

        $koperasiId = $koperasiModel->insert($data);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Pendaftaran Koperasi Baru',
            'notes' => 'Mengajukan koperasi baru "' . $data['nama_koperasi'] . '" untuk diferifikasi.',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Pendaftaran koperasi berhasil diajukan. Menunggu verifikasi Dinas Koperasi.',
            'koperasi_id' => $koperasiId
        ]);
    }

    public function updateStatus($id)
    {
        $koperasiModel = new KoperasiModel();
        $koperasi = $koperasiModel->find($id);

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

        $status = $this->request->getVar('status');
        $validStatuses = ['aktif', 'nonaktif', 'pending'];

        if (!in_array($status, $validStatuses)) {
            return $this->response->setJSON([
                'status' => 'error',
                'message' => 'Status tidak valid'
            ])->setStatusCode(400);
        }

        $koperasiModel->update($id, ['status' => $status]);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Ubah Status Koperasi',
            'notes' => 'Status Koperasi "' . $koperasi['nama_koperasi'] . '" diubah menjadi ' . $status,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Status Koperasi "' . $koperasi['nama_koperasi'] . '" diperbarui menjadi ' . $status
        ]);
    }

    public function updateProfile($id)
    {
        $koperasiModel = new KoperasiModel();
        $koperasi = $koperasiModel->find($id);

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

        $data = [
            'kode_koperasi' => $this->request->getVar('kode_koperasi') ?: $koperasi['kode_koperasi'],
            'nama_koperasi' => $this->request->getVar('nama_koperasi') ?: $koperasi['nama_koperasi'],
            'alamat' => $this->request->getVar('alamat') ?: $koperasi['alamat'],
            'kabupaten' => $this->request->getVar('kabupaten') ?: $koperasi['kabupaten'],
            'provinsi' => $this->request->getVar('provinsi') ?: $koperasi['provinsi'],
            'logo' => $this->request->getVar('logo') ?: $koperasi['logo'],
            'status' => $this->request->getVar('status') ?: $koperasi['status'],
            'payment_methods' => $this->request->getVar('payment_methods') !== null ? $this->request->getVar('payment_methods') : $koperasi['payment_methods'],
        ];

        $koperasiModel->update($id, $data);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Update Profil Koperasi',
            'notes' => 'Memperbarui informasi Koperasi "' . $data['nama_koperasi'] . '".',
            'created_at' => date('Y-m-d H:i:s')
        ]);

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

    public function delete($id)
    {
        $koperasiModel = new KoperasiModel();
        $koperasi = $koperasiModel->find($id);

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

        $koperasiModel->delete($id);

        // Add audit log
        $db = \Config\Database::connect();
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Hapus Koperasi',
            'notes' => 'Menghapus Koperasi "' . $koperasi['nama_koperasi'] . '".',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Koperasi "' . $koperasi['nama_koperasi'] . '" berhasil dihapus!'
        ]);
    }

    public function auditLogs()
    {
        $db = \Config\Database::connect();
        $logs = $db->table('audit_logs l')
            ->select('l.*, u.nama as user_name, r.role_name')
            ->join('users u', 'u.id = l.user_id', 'left')
            ->join('roles r', 'r.id = u.role_id', 'left')
            ->orderBy('l.id', 'DESC')
            ->get()
            ->getResultArray();

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

    public function clearAuditLogs()
    {
        $db = \Config\Database::connect();
        
        // Empty the table
        $db->table('audit_logs')->truncate();

        // Optional: you can add a log that the logs were cleared, so the table isn't entirely empty
        $db->table('audit_logs')->insert([
            'user_id' => $this->request->getVar('user_id') ?: null,
            'action' => 'Pembersihan Log Sistem',
            'notes' => 'Super Admin telah membersihkan seluruh riwayat audit log.',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->response->setJSON([
            'status' => 'success',
            'message' => 'Semua riwayat log berhasil dibersihkan.'
        ]);
    }
}
