<?php
defined('BASEPATH') or exit('No direct script access allowed');

class TicketSeeder extends BaseSeeder
{
    public function run()
    {
        $customers   = $this->db->select('userid')->get(db_prefix() . 'clients')->result_array();
        $staff       = $this->db->select('staffid')->where('active', 1)->get(db_prefix() . 'staff')->result_array();
        $departments = $this->db->select('departmentid')->get(db_prefix() . 'departments')->result_array();

        if (empty($customers) || empty($staff) || empty($departments)) {
            $this->log("! Need customers, staff, departments first.");
            return;
        }

        $subjects = [
            'Cannot log in to my account',       'Refund request for order #%d',
            'Feature request: dark mode',        'Bug in the export function',
            'Password reset link not working',   'Question about pricing plan',
            'Slow performance in dashboard',     'Invoice #%d shows wrong amount',
            'How to bulk import contacts?',      'API rate limit issue',
            'Email notifications not arriving',  'Two-factor auth not sending SMS',
            'Duplicate charge on my card',       'Integration with third party tool',
            'Cancel subscription request',       'Missing data after latest update',
            'Widget not loading on mobile',      'Cannot upload attachment',
            'Report generation failing',         'Domain verification stuck',
        ];
        $messages = [
            'Hi team, I need help with this issue. Can you please look into it as soon as possible?',
            'This has been happening for the last 3 days. Please advise on the next steps.',
            'I have tried the usual troubleshooting steps but nothing seems to work.',
            'Could someone from the technical team assist me with this? Thanks.',
            'This is affecting my daily workflow. Priority resolution requested.',
        ];

        $priorities = [1, 2, 3];
        $statusMix  = [1, 1, 1, 2, 2, 5, 5, 5, 5, 3, 4];
        $seeded     = 0;

        for ($i = 1; $i <= 60; $i++) {
            $cust     = $customers[array_rand($customers)];
            $assigned = $staff[array_rand($staff)]['staffid'];
            $dept     = $departments[array_rand($departments)]['departmentid'];
            $subject  = $subjects[array_rand($subjects)];
            if (strpos($subject, '%d') !== false) $subject = sprintf($subject, rand(1000, 9999));
            $priority = $priorities[array_rand($priorities)];
            $status   = $statusMix[array_rand($statusMix)];
            $daysAgo  = rand(0, 45);
            $created  = date('Y-m-d H:i:s', strtotime("-$daysAgo days"));

            $contact = $this->db->select('id')
                ->where('userid', $cust['userid'])
                ->where('is_primary', 1)
                ->get(db_prefix() . 'contacts')
                ->row();
            if (!$contact) continue;

            $lastReply = null;
            if (in_array($status, [2, 3, 5])) {
                $lastReply = date('Y-m-d H:i:s', strtotime($created . ' +' . rand(1, 72) . ' hours'));
            }

            $this->db->insert(db_prefix() . 'tickets', [
                'userid'     => $cust['userid'],
                'contactid'  => $contact->id,
                'department' => $dept,
                'priority'   => $priority,
                'status'     => $status,
                'subject'    => $subject,
                'message'    => $messages[array_rand($messages)],
                'admin'      => null,
                'date'       => $created,
                'lastreply'  => $lastReply,
                'assigned'   => $assigned,
                'ticketkey'  => strtoupper(substr(md5($i . microtime()), 0, 12)),
                'clientread' => 1,
                'adminread'  => 1,
            ]);
            $ticketid = $this->db->insert_id();

            if ($lastReply) {
                $this->db->insert(db_prefix() . 'ticket_replies', [
                    'ticketid'  => $ticketid,
                    'userid'    => $cust['userid'],
                    'contactid' => null,
                    'name'      => null,
                    'email'     => null,
                    'date'      => $lastReply,
                    'message'   => 'Thanks for reaching out. We are looking into this and will get back shortly.',
                    'admin'     => $assigned,
                ]);
            }
            $seeded++;
        }
        $this->log("+ Tickets seeded: $seeded");
    }
}
