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

class CompanyController {
    private function checkAuth($f3) {
        $isImpersonating = isset($_SESSION['original_super_admin']);
        $isCompanyAdmin = isset($_SESSION['user']) && $_SESSION['user']['role'] === 'company_admin';
        
        if (!$isCompanyAdmin && !$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();
        
        $domainModel = new \Models\Vehicle($db);
        $serviceModel = new \Models\Service($db);
        
        $company = $db->exec('SELECT * FROM companies WHERE id = ?', array($companyId));
        $company = $company ? $company[0] : array('name' => 'Company');
        
        $totalDomains = $domainModel->countByCompany($companyId);
        
        $dueThisMonth = $db->exec(
            "SELECT COUNT(*) as count 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 = ? AND s.next_service_date >= DATE_TRUNC('month', CURRENT_DATE) 
             AND s.next_service_date < DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month'",
            array($companyId)
        );
        $dueThisMonth = $dueThisMonth ? $dueThisMonth[0]['count'] : 0;
        
        $overdueReminders = $db->exec(
            "SELECT COUNT(*) as count 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 = ? AND s.next_service_date < CURRENT_DATE",
            array($companyId)
        );
        $overdueReminders = $overdueReminders ? $overdueReminders[0]['count'] : 0;
        
        $completedThisMonth = $db->exec(
            "SELECT COUNT(*) as count 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 = ? AND s.service_date >= DATE_TRUNC('month', CURRENT_DATE)",
            array($companyId)
        );
        $completedThisMonth = $completedThisMonth ? $completedThisMonth[0]['count'] : 0;
        
        $stats = [
            'total_vehicles' => $totalDomains,
            'due_this_month' => $dueThisMonth,
            'overdue_reminders' => $overdueReminders,
            'completed_this_month' => $completedThisMonth
        ];
        
        $months = array('Jul 2025', 'Aug 2025', 'Sep 2025', 'Oct 2025', 'Nov 2025', 'Dec 2025');
        $domainsDue = array(0, 0, 0, 1, 1, 2);
        $jobsCompleted = array(0, 0, 1, 1, 2, 4);
        
        $chartData = array(
            'months' => json_encode($months),
            'vehiclesDue' => json_encode($domainsDue),
            'jobsCompleted' => json_encode($jobsCompleted)
        );
        
        $f3->set('stats', $stats);
        $f3->set('company', $company);
        $f3->set('chartData', $chartData);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/dashboard.html');
    }
    
    public function staff($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $userModel = new \Models\User($db);
        $staffList = $userModel->findStaffByCompany($companyId);
        
        $f3->set('staffList', $staffList);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/staff.html');
    }
    
    public function customers($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $customerModel = new \Models\Customer($db);
        $customersList = $customerModel->findByCompany($companyId);
        
        $f3->set('customersList', $customersList);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/customers.html');
    }
    
    public function domains($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $domainModel = new \Models\Vehicle($db);
        $customerModel = new \Models\Customer($db);
        
        $domainsList = $domainModel->findByCompany($companyId);
        $customersList = $customerModel->findByCompany($companyId);
        
        $f3->set('vehiclesList', $domainsList);
        $f3->set('customersList', $customersList);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/domains.html');
    }
    
    public function services($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $serviceModel = new \Models\Service($db);
        $domainModel = new \Models\Vehicle($db);
        
        $servicesList = $serviceModel->findByCompany($companyId);
        $domainsList = $domainModel->findByCompany($companyId);
        
        $f3->set('servicesList', $servicesList);
        $f3->set('vehiclesList', $domainsList);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/services.html');
    }
    
    public function reminders($f3) {
        if (!$this->checkAuth($f3)) return;
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $reminderModel = new \Models\Reminder($db);
        $remindersList = $reminderModel->findPendingByCompany($companyId);
        
        $f3->set('remindersList', $remindersList);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/reminders.html');
    }
    
    public function settings($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' => '', 'address' => '', 'phone' => '');
        
        $f3->set('company', $company);
        $f3->set('user', $_SESSION['user']);
        $this->setImpersonatingFlag($f3);
        echo \Template::instance()->render('company/settings.html');
    }
    
    public function getStaffList($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $userModel = new \Models\User($db);
        $staffList = $userModel->findStaffByCompany($companyId);
        
        echo json_encode(array('success' => true, 'staff' => $staffList));
    }
    
    public function createStaff($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (empty($data['name']) || empty($data['email']) || empty($data['password'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Name, email and password are required']);
            return;
        }
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $userModel = new \Models\User($db);
        
        $existing = $userModel->findByEmail($data['email']);
        if ($existing) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Email already exists']);
            return;
        }
        
        try {
            $userModel->create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => $data['password'],
                'phone' => $data['phone'] ?? null,
                'role' => 'staff',
                'company_id' => $companyId
            ]);
            
            echo json_encode(['success' => true, 'message' => 'Staff member created successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create staff member: ' . $e->getMessage()]);
        }
    }
    
    public function updateStaff($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $userModel = new \Models\User($db);
        
        try {
            $updateData = [
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone']
            ];
            
            if (!empty($data['password'])) {
                $updateData['password'] = $data['password'];
            }
            
            $userModel->update($id, $updateData);
            echo json_encode(['success' => true, 'message' => 'Staff member updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update staff member']);
        }
    }
    
    public function deleteStaff($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $userModel = new \Models\User($db);
        
        try {
            $userModel->delete($id);
            echo json_encode(['success' => true, 'message' => 'Staff member deleted successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to delete staff member']);
        }
    }
    
    public function createCustomer($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $customerModel = new \Models\Customer($db);
        
        try {
            $customerModel->create([
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'company_id' => $companyId
            ]);
            echo json_encode(['success' => true, 'message' => 'Customer created successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create customer']);
        }
    }
    
    public function updateCustomer($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $customerModel = new \Models\Customer($db);
        
        try {
            $customerModel->update($id, [
                'name' => $data['name'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'address' => $data['address']
            ]);
            echo json_encode(['success' => true, 'message' => 'Customer updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update customer']);
        }
    }
    
    public function deleteCustomer($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $customerModel = new \Models\Customer($db);
        
        try {
            $customerModel->delete($id);
            echo json_encode(['success' => true, 'message' => 'Customer deleted successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to delete customer']);
        }
    }
    
    public function createVehicle($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $domainModel = new \Models\Vehicle($db);
        
        try {
            $domainModel->create([
                'customer_id' => $data['customer_id'],
                'registration_number' => $data['registration_number'],
                'make' => $data['make'],
                'model' => $data['model'],
                'year' => $data['year'],
                'vin' => $data['vin'] ?? null
            ]);
            echo json_encode(['success' => true, 'message' => 'Domain created successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create domain']);
        }
    }
    
    public function updateVehicle($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $domainModel = new \Models\Vehicle($db);
        
        try {
            $domainModel->update($id, [
                'customer_id' => $data['customer_id'],
                'registration_number' => $data['registration_number'],
                'make' => $data['make'],
                'model' => $data['model'],
                'year' => $data['year'],
                'vin' => $data['vin'] ?? null
            ]);
            echo json_encode(['success' => true, 'message' => 'Domain updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update domain']);
        }
    }
    
    public function deleteVehicle($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $domainModel = new \Models\Vehicle($db);
        
        try {
            $domainModel->delete($id);
            echo json_encode(['success' => true, 'message' => 'Domain deleted successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to delete domain']);
        }
    }
    
    public function createService($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $serviceModel = new \Models\Service($db);
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $serviceId = $serviceModel->create([
                'vehicle_id' => $data['vehicle_id'],
                'service_type' => $data['service_type'],
                'service_date' => $data['service_date'],
                'next_service_date' => $data['next_service_date'],
                'mileage' => $data['mileage'],
                'notes' => $data['notes'] ?? null,
                'cost' => $data['cost'] ?? 0
            ]);
            
            if (!empty($data['next_service_date'])) {
                $reminderModel->createFromService($serviceId, $data['next_service_date']);
            }
            
            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']);
        }
    }
    
    public function updateService($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        
        try {
            $sets = [];
            $params_arr = [];
            
            $allowedFields = ['vehicle_id', 'service_type', 'service_date', 'next_service_date', 'mileage', 'notes', 'cost', 'status'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $sets[] = "$field = ?";
                    $params_arr[] = $data[$field];
                }
            }
            
            if (!empty($sets)) {
                $sets[] = 'updated_at = CURRENT_TIMESTAMP';
                $params_arr[] = $id;
                $db->exec('UPDATE services SET ' . implode(', ', $sets) . ' WHERE id = ?', $params_arr);
            }
            
            echo json_encode(['success' => true, 'message' => 'Service record updated successfully']);
        } catch (\Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update service record']);
        }
    }
    
    public function deleteService($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        
        $db = $f3->get('DB');
        
        try {
            // First verify the service belongs to this company
            $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 = ?',
                [$id, $companyId]
            );
            
            if (!$serviceCheck) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Service record not found']);
                return;
            }
            
            // Delete associated reminders first
            $db->exec('DELETE FROM reminders WHERE service_id = ?', [$id]);
            
            // Then delete the service
            $db->exec('DELETE FROM services WHERE id = ?', [$id]);
            
            echo json_encode(['success' => true, 'message' => 'Service record deleted successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to delete service record']);
        }
    }
    
    public function createReminder($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminderModel->create([
                'service_id' => $data['service_id'],
                'scheduled_date' => $data['scheduled_date'],
                'reminder_type' => $data['reminder_type'],
                'message' => $data['message'] ?? null
            ]);
            echo json_encode(['success' => true, 'message' => 'Reminder created successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create reminder']);
        }
    }
    
    public function updateReminder($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminderModel->updateStatus($id, $data['status']);
            echo json_encode(['success' => true, 'message' => 'Reminder updated successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update reminder']);
        }
    }
    
    public function deleteReminder($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminderModel->delete($id);
            echo json_encode(['success' => true, 'message' => 'Reminder deleted successfully']);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to delete reminder']);
        }
    }
    
    public function sendWhatsApp($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        $companyId = $this->getCompanyId();
        
        try {
            $reminder = $reminderModel->findById($id);
            if (!$reminder) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $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 = ?',
                [$id, $companyId]
            );
            
            if (!$reminderCheck) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                return;
            }
            
            $reminderModel->logAction($id, 'whatsapp_sent', $_SESSION['user']['id'], 'WhatsApp message sent');
            $reminderModel->updateTypeAndStatus($id, 'whatsapp', 'sent');
            
            $phone = preg_replace('/[^0-9]/', '', $reminder['customer_phone']);
            if (empty($phone)) {
                echo json_encode(['success' => false, 'message' => 'Customer phone number not found']);
                return;
            }
            
            $defaultMessage = "Hi {customer_name}, this is a reminder for your {domain} ({registration}). Your {service_type} is due on {due_date}. Please book an appointment.";
            
            // Try to get custom template, but don't fail if system_settings doesn't have the expected columns
            try {
                $templateResult = $db->exec(
                    'SELECT value FROM system_settings WHERE key = ?',
                    ['company_' . $companyId . '_templates']
                );
                
                if ($templateResult && !empty($templateResult[0]['value'])) {
                    $templates = json_decode($templateResult[0]['value'], true);
                    if (isset($templates['whatsapp']) && !empty($templates['whatsapp'])) {
                        $defaultMessage = $templates['whatsapp'];
                    }
                }
            } catch (\Exception $e) {
                // Use default message if template query fails
            }
            
            $message = str_replace(
                ['{customer_name}', '{domain}', '{registration}', '{service_type}', '{due_date}'],
                [
                    $reminder['customer_name'] ?? '',
                    ($reminder['make'] ?? '') . ' ' . ($reminder['model'] ?? ''),
                    $reminder['registration_number'] ?? '',
                    $reminder['service_type'] ?? '',
                    $reminder['next_service_date'] ?? ''
                ],
                $defaultMessage
            );
            
            echo json_encode([
                'success' => true, 
                'message' => 'WhatsApp reminder sent',
                'whatsapp_url' => "https://wa.me/{$phone}?text=" . urlencode($message)
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to send WhatsApp reminder: ' . $e->getMessage()]);
        }
    }
    
    public function logCall($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $data = json_decode(file_get_contents('php://input'), true);
        $companyId = $this->getCompanyId();
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminder = $reminderModel->findById($id);
            if (!$reminder) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $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 = ?',
                [$id, $companyId]
            );
            
            if (!$reminderCheck) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                return;
            }
            
            $reminderModel->logAction($id, 'call_logged', $_SESSION['user']['id'], $data['notes'] ?? 'Call made to customer');
            $reminderModel->updateTypeAndStatus($id, 'call', 'sent');
            
            echo json_encode([
                'success' => true, 
                'message' => 'Call logged successfully',
                'phone' => $reminder['customer_phone']
            ]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to log call']);
        }
    }
    
    public function markReminderSent($f3, $params) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $id = $params['id'];
        $companyId = $this->getCompanyId();
        
        $db = $f3->get('DB');
        $reminderModel = new \Models\Reminder($db);
        
        try {
            $reminder = $reminderModel->findById($id);
            if (!$reminder) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Reminder not found']);
                return;
            }
            
            $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 = ?',
                [$id, $companyId]
            );
            
            if (!$reminderCheck) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Access denied']);
                return;
            }
            
            $reminderModel->updateStatus($id, 'sent');
            $reminderModel->logAction($id, 'marked_sent', $_SESSION['user']['id'], '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']);
        }
    }
    
    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;
        
        $reminderModel = new \Models\Reminder($db);
        $reminders = $reminderModel->findByCompanyWithFilter($companyId, $type);
        
        echo json_encode(['success' => true, 'reminders' => $reminders ?: []]);
    }
    
    public function getServices($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        $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.created_at DESC',
            [$companyId]
        );
        
        echo json_encode(['success' => true, 'services' => $services]);
    }
    
    public function createServiceWithCustomer($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        try {
            $existingCustomer = $db->exec(
                'SELECT id FROM customers WHERE phone = ? AND company_id = ?',
                [$data['customer_phone'], $companyId]
            );
            
            if ($existingCustomer) {
                $customerId = $existingCustomer[0]['id'];
            } else {
                $db->exec(
                    'INSERT INTO customers (company_id, name, phone, created_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)',
                    [$companyId, $data['customer_name'], $data['customer_phone']]
                );
                $customerId = $db->lastinsertid();
            }
            
            $existingDomain = $db->exec(
                'SELECT id FROM domains WHERE registration_number = ? AND customer_id = ?',
                [$data['registration_number'], $customerId]
            );
            
            if ($existingDomain) {
                $vehicleId = $existingDomain[0]['id'];
                $db->exec(
                    'UPDATE domains SET make = ?, model = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
                    [$data['make'] ?? null, $data['model'] ?? null, $vehicleId]
                );
            } else {
                $db->exec(
                    'INSERT INTO domains (customer_id, registration_number, make, model, created_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)',
                    [$customerId, $data['registration_number'], $data['make'] ?? null, $data['model'] ?? null]
                );
                $vehicleId = $db->lastinsertid();
            }
            
            $db->exec(
                'INSERT INTO services (vehicle_id, service_type, service_date, next_service_date, notes, status, created_at) VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)',
                [$vehicleId, $data['service_type'], $data['service_date'], $data['next_service_date'], $data['notes'] ?? null, $data['status'] ?? 'pending']
            );
            $serviceId = $db->lastinsertid();
            
            if (!empty($data['next_service_date'])) {
                $reminderModel = new \Models\Reminder($db);
                $reminderModel->createFromService($serviceId, $data['next_service_date']);
            }
            
            echo json_encode(['success' => true, 'message' => 'Service record created successfully', 'service_id' => $serviceId]);
        } catch (\Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to create service record: ' . $e->getMessage()]);
        }
    }
    
    public function updateBusinessInfo($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        try {
            $sets = [];
            $params = [];
            
            if (isset($data['business_name'])) {
                $sets[] = 'name = ?';
                $params[] = $data['business_name'];
            }
            if (isset($data['address'])) {
                $sets[] = 'address = ?';
                $params[] = $data['address'];
            }
            if (isset($data['whatsapp_number'])) {
                $sets[] = 'phone = ?';
                $params[] = $data['whatsapp_number'];
            }
            
            if (!empty($sets)) {
                $sets[] = 'updated_at = CURRENT_TIMESTAMP';
                $params[] = $companyId;
                $db->exec('UPDATE companies SET ' . implode(', ', $sets) . ' WHERE id = ?', $params);
            }
            
            echo json_encode(['success' => true, 'message' => 'Business info updated successfully']);
        } catch (\Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to update business info']);
        }
    }
    
    public function updateTemplates($f3) {
        if (!$this->checkAuth($f3)) return;
        
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        
        $db = $f3->get('DB');
        $companyId = $this->getCompanyId();
        
        try {
            $templateData = json_encode([
                'reminder_offsets' => $data['reminder_offsets'] ?? '30, 14, 7',
                'friendly_template' => $data['friendly_template'] ?? '',
                'formal_template' => $data['formal_template'] ?? ''
            ]);
            
            $exists = $db->exec('SELECT 1 FROM system_settings WHERE key = ?', ['company_' . $companyId . '_templates']);
            
            if ($exists) {
                $db->exec(
                    'UPDATE system_settings SET value = ?, updated_at = CURRENT_TIMESTAMP WHERE key = ?',
                    [$templateData, 'company_' . $companyId . '_templates']
                );
            } else {
                $db->exec(
                    'INSERT INTO system_settings (key, value, created_at) VALUES (?, ?, CURRENT_TIMESTAMP)',
                    ['company_' . $companyId . '_templates', $templateData]
                );
            }
            
            echo json_encode(['success' => true, 'message' => 'Templates saved successfully']);
        } catch (\Exception $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Failed to save templates']);
        }
    }
}
