<?php
namespace App\Controllers;

class BinController extends BaseController
{
    public function index()
    {
        $db  = db_connect();
        $cid = $this->companyId;
        $entityType = $this->request->getGet('entity_type');

        $b = $db->table('deleted_items')
                ->where('company_id',$cid)
                ->where('purged_at IS NULL',null,false)
                ->orderBy('deleted_at','DESC');
        if ($entityType) $b->where('entity_type',$entityType);
        $items = $b->get()->getResultArray();

        return $this->view('bin/index', compact('items','entityType'));
    }

    public function restore(int $id)
    {
        $db   = db_connect();
        $item = $db->table('deleted_items')
                   ->where('id',$id)
                   ->where('company_id',$this->companyId)
                   ->get()->getRowArray();

        if (!$item) return redirect()->back()->with('error','Not found.');

        $tableMap = [
            'job'      => 'jobs',
            'customer' => 'customers',
            'quote'    => 'quotes',
            'invoice'  => 'invoices',
        ];

        $table = $tableMap[$item['entity_type']] ?? null;
        if ($table) {
            // Just clear deleted_at on the original row
            $db->table($table)
               ->where('id',(int)$item['entity_id'])
               ->update(['deleted_at' => null]);
        }

        $db->table('deleted_items')
           ->where('id',$id)
           ->update([
               'restored_at' => date('Y-m-d H:i:s'),
               'restored_by' => $this->userId,
           ]);

        return redirect()->back()->with('success', ucfirst($item['entity_type']).' restored.');
    }

    public function purge(int $id)
    {
        $db   = db_connect();
        $item = $db->table('deleted_items')
                   ->where('id',$id)
                   ->where('company_id',$this->companyId)
                   ->get()->getRowArray();

        if (!$item) return redirect()->back()->with('error','Not found.');

        $db->table('deleted_items')
           ->where('id',$id)
           ->update(['purged_at' => date('Y-m-d H:i:s')]);

        return redirect()->back()->with('success','Permanently deleted.');
    }

    public function purgeAll()
    {
        db_connect()->table('deleted_items')
            ->where('company_id',$this->companyId)
            ->where('purged_at IS NULL',null,false)
            ->update(['purged_at' => date('Y-m-d H:i:s')]);

        return redirect()->back()->with('success','Recycle bin emptied.');
    }
}