<?php
/**
 * ImportController — bulk-load trucks, drivers, and customers from an
 * Excel spreadsheet. Client parses the .xlsx with SheetJS then POSTs the
 * parsed rows here as JSON. Server validates each row and inserts through
 * the same model methods used by the interactive forms.
 *
 * Design note: we do NOT accept the raw .xlsx file on the server — that
 * would need PhpSpreadsheet in the request path. Instead the client parses
 * with SheetJS (already local at js/Olibs/xlsx.full.min.js) and posts a
 * clean JSON array. This keeps the server dependency-light.
 */
class ImportController extends Controller
{
    public function indexAction()
    {
        $entity = $_GET['entity'] ?? 'trucks';
        if (!in_array($entity, ['trucks','drivers','customers'], true)) $entity = 'trucks';

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Import/index', [
            'page_title' => 'Data Import',
            'entity'     => $entity,
            'columns'    => $this->columnsFor($entity),
        ]);
    }

    /* ---- POST endpoints (Vue posts JSON, we validate + insert) ---- */

    public function trucksAjAction()      { $this->doImport('trucks'); }
    public function driversAjAction()     { $this->doImport('drivers'); }
    public function customersAjAction()   { $this->doImport('customers'); }

    /* =========================================================
     *  Core: validate + insert rows, return per-row outcomes
     * ========================================================= */
    private function doImport(string $entity): void
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { $this->jsonResponse(['ok'=>false, 'msg'=>'POST only.']); return; }

        // Rows arrive JSON-encoded as $_POST['rows'] (Vue posts via FormData).
        $rows = json_decode((string)($_POST['rows'] ?? '[]'), true);
        // jsonResponse() calls exit() internally, so `return` is unnecessary — and
        // in fact fatal, because jsonResponse is declared void in the base Controller.
        if (!is_array($rows))    { $this->jsonResponse(['ok'=>false, 'msg'=>'Invalid payload — rows must be a JSON array.']); return; }
        if (count($rows) === 0)  { $this->jsonResponse(['ok'=>false, 'msg'=>'No rows to import.']);                            return; }
        if (count($rows) > 5000) { $this->jsonResponse(['ok'=>false, 'msg'=>'Too many rows in one batch (limit 5000).']);      return; }

        $uid   = $this->currentUserId();
        $out   = ['imported' => 0, 'failed' => 0, 'results' => []];

        foreach ($rows as $i => $row) {
            $rowNo = $i + 2;    // spreadsheet row (1-indexed + header row)
            if (!is_array($row)) { $out['failed']++; $out['results'][] = ['row'=>$rowNo, 'ok'=>false, 'msg'=>'Row is not an object.']; continue; }

            // Normalise: strip whitespace-only keys, coerce keys to snake_case
            $clean = [];
            foreach ($row as $k => $v) {
                $key = strtolower(trim((string)$k));
                $key = preg_replace('/[^a-z0-9]+/', '_', $key);
                $key = trim($key, '_');
                $clean[$key] = is_string($v) ? trim($v) : $v;
            }

            $r = match ($entity) {
                'trucks'    => (new Trucks())->create($clean, $uid),
                'drivers'   => (new Drivers())->create($clean, $uid),
                'customers' => (new Customers())->create($clean, $uid),
            };

            if ($r['ok']) { $out['imported']++; $out['results'][] = ['row'=>$rowNo, 'ok'=>true,  'id'=>$r['id']]; }
            else          { $out['failed']++;   $out['results'][] = ['row'=>$rowNo, 'ok'=>false, 'msg'=>$r['msg']]; }
        }

        $out['ok']  = true;
        $out['msg'] = "Imported {$out['imported']} · failed {$out['failed']}";
        $this->jsonResponse($out);
    }

    /* =========================================================
     *  Column specs — drive the download-template button + preview headers.
     *  Field names match the columns the model.create() methods expect.
     *  '*' marks a required field.
     * ========================================================= */
    private function columnsFor(string $entity): array
    {
        return match ($entity) {
            'trucks' => [
                ['field'=>'reg_no',           'label'=>'Reg No*',            'sample'=>'T 999 ABC'],
                ['field'=>'make',             'label'=>'Make',               'sample'=>'Isuzu'],
                ['field'=>'model',            'label'=>'Model',              'sample'=>'FVR34'],
                ['field'=>'year',             'label'=>'Year',               'sample'=>'2022'],
                ['field'=>'chassis_no',       'label'=>'Chassis No',         'sample'=>'JAAFRR33XN7100001'],
                ['field'=>'engine_no',        'label'=>'Engine No',          'sample'=>'6HK1-543210'],
                ['field'=>'colour',           'label'=>'Colour',             'sample'=>'White'],
                ['field'=>'tare_kg',          'label'=>'Tare (kg)',          'sample'=>'8500'],
                ['field'=>'capacity_kg',      'label'=>'Capacity (kg)',      'sample'=>'15000'],
                ['field'=>'fuel_tank_liters', 'label'=>'Fuel Tank (L)',      'sample'=>'400'],
                ['field'=>'current_odometer', 'label'=>'Odometer (km)',      'sample'=>'45000'],
                ['field'=>'ownership',        'label'=>'Ownership',          'sample'=>'owned'],
                ['field'=>'status',           'label'=>'Status',             'sample'=>'active'],
                ['field'=>'notes',            'label'=>'Notes',              'sample'=>''],
            ],
            'drivers' => [
                ['field'=>'full_name',        'label'=>'Full Name*',         'sample'=>'John Mwakalinga'],
                ['field'=>'employee_no',      'label'=>'Employee No',        'sample'=>'EMP-101'],
                ['field'=>'id_no',            'label'=>'National ID',        'sample'=>'19850101-12345-67890'],
                ['field'=>'phone_1',          'label'=>'Phone',              'sample'=>'+255 787 000 000'],
                ['field'=>'phone_2',          'label'=>'Phone (alt)',        'sample'=>''],
                ['field'=>'email',            'label'=>'Email',              'sample'=>'john@example.com'],
                ['field'=>'dob',              'label'=>'Date of Birth',      'sample'=>'1985-01-01'],
                ['field'=>'gender',           'label'=>'Gender',             'sample'=>'male'],
                ['field'=>'address',          'label'=>'Address',            'sample'=>'Kariakoo'],
                ['field'=>'city',             'label'=>'City',               'sample'=>'Dar es Salaam'],
                ['field'=>'country',          'label'=>'Country',            'sample'=>'TANZANIA'],
                ['field'=>'next_of_kin_name', 'label'=>'Next of Kin',        'sample'=>'Anna Mwakalinga'],
                ['field'=>'next_of_kin_phone','label'=>'Next of Kin Phone',  'sample'=>'+255 787 111 111'],
                ['field'=>'licence_no',       'label'=>'Licence No',         'sample'=>'TZ-000123'],
                ['field'=>'licence_class',    'label'=>'Licence Class',      'sample'=>'C'],
                ['field'=>'licence_expires',  'label'=>'Licence Expires',    'sample'=>'2027-06-30'],
                ['field'=>'hire_date',        'label'=>'Hire Date',          'sample'=>'2022-03-15'],
                ['field'=>'status',           'label'=>'Status',             'sample'=>'available'],
                ['field'=>'notes',            'label'=>'Notes',              'sample'=>''],
            ],
            'customers' => [
                ['field'=>'fname',              'label'=>'Company Name*',        'sample'=>'Twiga Cement Ltd'],
                ['field'=>'lname',              'label'=>'Trading Name',         'sample'=>'Twiga'],
                ['field'=>'customer_code',      'label'=>'Customer Code',        'sample'=>'TWG-01'],
                ['field'=>'customer_tin',       'label'=>'TIN',                  'sample'=>'123-456-789'],
                ['field'=>'customer_vrn',       'label'=>'VRN',                  'sample'=>'40-000123-P'],
                ['field'=>'customer_sector',    'label'=>'Sector',               'sample'=>'CONSTRUCTION'],
                ['field'=>'customer_tier',      'label'=>'Tier',                 'sample'=>'CORPORATE'],
                ['field'=>'email',              'label'=>'Email',                'sample'=>'ap@twiga.co.tz'],
                ['field'=>'phone_1',            'label'=>'Phone',                'sample'=>'+255 22 000 0000'],
                ['field'=>'physical_address',   'label'=>'Address',              'sample'=>'Nyerere Road'],
                ['field'=>'city',               'label'=>'City',                 'sample'=>'Dar es Salaam'],
                ['field'=>'country',            'label'=>'Country',              'sample'=>'TANZANIA'],
                ['field'=>'customer_poc',       'label'=>'Contact Person',       'sample'=>'Aisha Mwakalinga'],
                ['field'=>'customer_poc_phone', 'label'=>'Contact Phone',        'sample'=>'+255 787 000 000'],
                ['field'=>'customer_poc_email', 'label'=>'Contact Email',        'sample'=>'aisha@twiga.co.tz'],
                ['field'=>'currency',           'label'=>'Currency',             'sample'=>'TZS'],
                ['field'=>'credit_limit',       'label'=>'Credit Limit',         'sample'=>'15000000'],
                ['field'=>'payment_terms_days', 'label'=>'Payment Terms (days)', 'sample'=>'30'],
                ['field'=>'opening_balance',    'label'=>'Opening Balance',      'sample'=>'0'],
                ['field'=>'notes',              'label'=>'Notes',                'sample'=>''],
            ],
        };
    }
}
