<?php
require_once __DIR__ . '/../models/Service.php';
require_once __DIR__ . '/../models/Reminder.php';

class StaffController {
    private function checkAuth($f3) {
        $isImpersonating = isset($_SESSION['original_super_admin']);
        $isStaff = isset($_SESSION['user']) && $_SESSION['user']['role'] === 'staff';
        
        if (!$isStaff && !$isImpersonating) {
            $f3->reroute('/login');
            return false;
        }
        return true;
    }
    
    private function setImpersonatingFlag($f3) {
        $f3->set('is_impersonating', isset($_SESSION['original_super_admin']));
    }
    
    private function getCompanyId() {
        return $_SESSION['user']['company_id'];
    }
    
    public function dashboard($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $company = $db->exec('SELECT * FROM companies WHERE id = ?', array($companyId));
        $company = $company ? $company[0] : array('name' => 'Company');
        
        $serviceModel = new \Models\Service($db);
        $reminderModel = new \Models\Reminder($db);
        
        $todayServices = $serviceModel->findTodayByCompany($companyId);
        $overdueServices = $serviceModel->findOverdueByCompany($companyId);
        $pendingReminders = $reminderModel->findPendingByCompany($companyId);
        
        $stats = [
            'today_count' => count($todayServices),
            'overdue_count' => count($overdueServices),
            'pending_reminders' => count($pendingReminders)
        ];
        
        $f3->set('stats', $stats);
        $f3->set('company', $company);
        $f3->set('todayServices', $todayServices);
        $f3->set('overdueServices', $overdueServices);
        $f3->set('pendingReminders', $pendingReminders);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('staff/dashboard.html');
    }
    
    public function services($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        $company = $db->exec('SELECT * FROM companies WHERE id = ?', array($companyId));
        $company = $company ? $company[0] : array('name' => 'Company');
        
        $f3->set('company', $company);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('staff/services.html');
    }
    
    public function reminders($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        $company = $db->exec('SELECT * FROM companies WHERE id = ?', array($companyId));
        $company = $company ? $company[0] : array('name' => 'Company');
        
        $f3->set('company', $company);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('staff/reminders.html');
    }
    
    public function getServices($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        try {
            $services = $db->exec(
                "SELECT s.*, v.registration_number, v.make, v.model, c.name as customer_name, c.phone as customer_phone 
                 FROM services s 
                 INNER JOIN domains v ON s.vehicle_id = v.id 
                 INNER JOIN customers c ON v.customer_id = c.id 
                 WHERE c.company_id = ? 
                 ORDER BY s.next_service_date DESC",
                array($companyId)
            );
            
            echo json_encode(['success' => true, 'services' => $services ?: []]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to load services']);
        }
    }
    
    public function createService($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        $data = json_decode(file_get_contents('php://input'), true);
        
        // Validate required fields
        if (empty($data['customer_name']) || trim($data['customer_name']) === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Customer name is required']);
            return;
        }
        if (empty($data['customer_phone']) || trim($data['customer_phone']) === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Customer phone is required']);
            return;
        }
        if (empty($data['registration_number']) || trim($data['registration_number']) === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Domain domain is required']);
            return;
        }
        if (empty($data['service_type']) || trim($data['service_type']) === '') {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Service type is required']);
            return;
        }
        if (empty($data['service_date'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Service date is required']);
            return;
        }
        
        try {
            $customerResult = $db->exec(
                "SELECT id FROM customers WHERE phone = ? AND company_id = ?",
                array($data['customer_phone'], $companyId)
            );
            
            if ($customerResult) {
                $customerId = $customerResult[0]['id'];
            } else {
                $db->exec(
                    "INSERT INTO customers (company_id, name, phone, created_at) VALUES (?, ?, ?, NOW())",
                    array($companyId, trim($data['customer_name']), trim($data['customer_phone']))
                );
                $lastId = $db->exec("SELECT lastval() as id");
                $customerId = $lastId[0]['id'];
            }
            
            $domainResult = $db->exec(
                "SELECT id FROM domains WHERE registration_number = ? AND customer_id = ?",
                array($data['registration_number'], $customerId)
            );
            
            if ($domainResult) {
                $vehicleId = $domainResult[0]['id'];
            } else {
                $db->exec(
                    "INSERT INTO domains (customer_id, registration_number, make, model, created_at) VALUES (?, ?, ?, ?, NOW())",
                    array($customerId, trim($data['registration_number']), $data['make'] ?? '', $data['model'] ?? '')
                );
                $lastId = $db->exec("SELECT lastval() as id");
                $vehicleId = $lastId[0]['id'];
            }
            
            $db->exec(
                "INSERT INTO services (vehicle_id, service_type, service_date, next_service_date, notes, status, created_at) VALUES (?, ?, ?, ?, ?, ?, NOW())",
                array($vehicleId, trim($data['service_type']), $data['service_date'], $data['next_service_date'] ?? null, $data['notes'] ?? '', $data['status'] ?? 'pending')
            );
            
            echo json_encode(['success' => true, 'message' => 'Service record created successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create service record: ' . $e->getMessage()]);
        }
    }
    
    public function updateService($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        $data = json_decode(file_get_contents('php://input'), true);
        
        try {
            $serviceCheck = $db->exec(
                "SELECT s.id FROM services s 
                 INNER JOIN domains v ON s.vehicle_id = v.id 
                 INNER JOIN customers c ON v.customer_id = c.id 
                 WHERE s.id = ? AND c.company_id = ?",
                array($id, $companyId)
            );
            
            if (!$serviceCheck) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Service record not found']);
                return;
            }
            
            $updates = [];
            $updateParams = [];
            
            if (isset($data['status'])) {
                $updates[] = "status = ?";
                $updateParams[] = $data['status'];
            }
            if (isset($data['service_type'])) {
                $updates[] = "service_type = ?";
                $updateParams[] = $data['service_type'];
            }
            if (isset($data['service_date'])) {
                $updates[] = "service_date = ?";
                $updateParams[] = $data['service_date'];
            }
            if (isset($data['next_service_date'])) {
                $updates[] = "next_service_date = ?";
                $updateParams[] = $data['next_service_date'];
            }
            if (isset($data['notes'])) {
                $updates[] = "notes = ?";
                $updateParams[] = $data['notes'];
            }
            
            if (!empty($updates)) {
                $updates[] = "updated_at = CURRENT_TIMESTAMP";
                $updateParams[] = $id;
                $sql = "UPDATE services SET " . implode(', ', $updates) . " WHERE id = ?";
                $db->exec($sql, $updateParams);
            }
            
            echo json_encode(['success' => true, 'message' => 'Service updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update service']);
        }
    }
    
    public function getReminders($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $type = isset($_GET['type']) ? $_GET['type'] : null;
        
        try {
            $reminderModel = new \Models\Reminder($db);
            $reminders = $reminderModel->findByCompanyWithFilter($companyId, $type);
            
            echo json_encode(['success' => true, 'reminders' => $reminders ?: []]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to load reminders']);
        }
    }
    
    public function sendWhatsApp($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        $staffId = $_SESSION['user']['id'];
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminder = $db->exec(
                "SELECT r.*, s.service_type, s.next_service_date, v.registration_number, c.name as customer_name, c.phone as customer_phone, c.company_id 
                 FROM reminders r 
                 INNER JOIN services s ON r.service_id = s.id 
                 INNER JOIN domains v ON s.vehicle_id = v.id 
                 INNER JOIN customers c ON v.customer_id = c.id 
                 WHERE r.id = ? AND c.company_id = ?",
                array($id, $companyId)
            );
            
            if (!$reminder) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $r = $reminder[0];
            $phone = preg_replace('/[^0-9]/', '', $r['customer_phone'] ?? '');
            $message = "Hi {$r['customer_name']}, this is a reminder for your domain {$r['registration_number']}. Your {$r['service_type']} service is due on {$r['next_service_date']}. Please schedule your appointment.";
            $whatsappUrl = 'https://wa.me/' . $phone . '?text=' . urlencode($message);
            
            $reminderModel->logAction($id, 'whatsapp_sent', $staffId, 'WhatsApp message sent');
            $reminderModel->updateTypeAndStatus($id, 'whatsapp', 'sent');
            
            echo json_encode(['success' => true, 'message' => 'WhatsApp reminder sent successfully', 'whatsapp_url' => $whatsappUrl]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to send WhatsApp reminder']);
        }
    }
    
    public function logCall($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        $staffId = $_SESSION['user']['id'];
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminderCheck = $db->exec(
                "SELECT r.id, c.phone as customer_phone FROM reminders r 
                 INNER JOIN services s ON r.service_id = s.id 
                 INNER JOIN domains v ON s.vehicle_id = v.id 
                 INNER JOIN customers c ON v.customer_id = c.id 
                 WHERE r.id = ? AND c.company_id = ?",
                array($id, $companyId)
            );
            
            if (!$reminderCheck) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $reminderModel->logAction($id, 'call_logged', $staffId, $data['notes'] ?? 'Call made to customer');
            $reminderModel->updateTypeAndStatus($id, 'call', 'sent');
            
            echo json_encode(['success' => true, 'message' => 'Call logged successfully', 'phone' => $reminderCheck[0]['customer_phone'] ?? '']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to log call']);
        }
    }
    
    public function markSent($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        $staffId = $_SESSION['user']['id'];
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminderCheck = $db->exec(
                "SELECT r.id FROM reminders r 
                 INNER JOIN services s ON r.service_id = s.id 
                 INNER JOIN domains v ON s.vehicle_id = v.id 
                 INNER JOIN customers c ON v.customer_id = c.id 
                 WHERE r.id = ? AND c.company_id = ?",
                array($id, $companyId)
            );
            
            if (!$reminderCheck) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $reminderModel->updateStatus($id, 'sent');
            $reminderModel->logAction($id, 'marked_sent', $staffId, 'Reminder marked as sent');
            
            echo json_encode(['success' => true, 'message' => 'Reminder marked as sent']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to mark reminder as sent']);
        }
    }
}
