<?php
declare(strict_types=1);

// Christo Lochenberg Developments | info@christodev.co.za | +27 61 523 9126

class AdminPartners extends Controller {
    
    private $partnerModel;
    private $userModel;

    public function __construct() {
        if (!isLoggedIn() || !isAdmin()) {
            header('Location: ' . URLROOT . '/users/login');
            exit;
        }

        $this->partnerModel = $this->model('Partner');
        $this->userModel = $this->model('User');
    }

    public function partners(): void {
        $data = [
            'title' => 'Subcontracting Partners',
            'description' => 'Manage external agencies, partner companies, and their custom jobcard sequences.',
            'partners' => $this->partnerModel->getPartners(),
            
            'help_title' => 'Partner Management Guide',
            'help_content' => '
                <h4 class="font-bold text-gray-800 dark:text-gray-200 mt-0">Partner Agencies</h4>
                <p>This module allows you to manage the subcontracting companies you work with.</p>
                <ul class="list-disc pl-5 space-y-2 mt-2">
                    <li><strong>Custom Numbering:</strong> You can assign a specific prefix (e.g., AGT-) and a starting sequence number. Any jobcards linked to this partner will use this numbering convention instead of the main system sequence.</li>
                    <li><strong>Co-Branding:</strong> Upload a logo for the partner. The finalized PDF jobcards will display their logo and contact details at the top instead of yours.</li>
                    <li><strong>Linking Clients:</strong> Once a partner is created here, you can link any Client account to them via the User Matrix.</li>
                </ul>
            '
        ];

        $this->view('admin/partners/index', $data);
    }

    public function addPartner(): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            
            $data = [
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email'] ?? ''),
                'password' => trim($_POST['password'] ?? ''),
                'contact_number' => trim($_POST['contact_number'] ?? ''),
                'address_street' => trim($_POST['address_street'] ?? ''),
                'address_suburb' => trim($_POST['address_suburb'] ?? ''),
                'address_city' => trim($_POST['address_city'] ?? ''),
                'address_state' => trim($_POST['address_state'] ?? ''),
                'address_zip' => trim($_POST['address_zip'] ?? ''),
                'address_country' => trim($_POST['address_country'] ?? ''),
                'jobcard_prefix' => trim($_POST['jobcard_prefix'] ?? 'PRT-'),
                'jobcard_sequence' => empty($_POST['jobcard_sequence']) ? 1 : (int)$_POST['jobcard_sequence'],
                'logo' => '',
                'name_err' => '',
                'email_err' => '',
                'password_err' => ''
            ];

            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter a partner name.';
            }

            if (empty($data['email'])) {
                $data['email_err'] = 'An email address is required to create the agency login.';
            } elseif ($this->userModel->findUserByEmail($data['email'])) {
                $data['email_err'] = 'This email is already registered to an existing user.';
            }

            if (empty($data['password']) || strlen($data['password']) < 6) {
                $data['password_err'] = 'Please provide an initial password of at least 6 characters.';
            }

            // --- FILE UPLOAD LOGIC FOR LOGO ---
            if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === 0) {
                $uploadDir = '../public/uploads/';
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $fileType = mime_content_type($_FILES['logo']['tmp_name']);
                
                if (in_array($fileType, $allowedTypes)) {
                    $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                    $filename = 'partner_' . time() . '.' . $ext;
                    if (move_uploaded_file($_FILES['logo']['tmp_name'], $uploadDir . $filename)) {
                        $data['logo'] = $filename;
                    }
                }
            }

            if (empty($data['name_err']) && empty($data['email_err']) && empty($data['password_err'])) {
                
                // 1. Create the Partner Agency Record
                $newPartnerId = $this->partnerModel->addPartnerReturnId($data);

                if ($newPartnerId) {
                    
                    // 2. Create the User Login Linked to the Agency
                    $userData = [
                        'name' => $data['name'],
                        'company_name' => '', // Partners do not use company_name
                        'email' => $data['email'],
                        'password' => password_hash($data['password'], PASSWORD_DEFAULT),
                        'role' => 'partner',
                        'is_active' => 1,
                        'contact_number' => $data['contact_number'],
                        'address_street' => $data['address_street'],
                        'address_suburb' => $data['address_suburb'],
                        'address_city' => $data['address_city'],
                        'address_state' => $data['address_state'],
                        'address_zip' => $data['address_zip'],
                        'address_country' => $data['address_country'],
                        'staff_role_id' => null,
                        'partner_id' => $newPartnerId
                    ];

                    if ($this->userModel->addUserByAdmin($userData)) {
                        
                        // 3. Queue Welcome / Password Reset Email
                        $token = bin2hex(random_bytes(32));
                        $this->userModel->addPasswordReset($data['email'], $token);
                        
                        $resetLink = URLROOT . '/users/resetPassword/' . $token;
                        $appName = getSettings()['app_name'] ?? SITENAME;
                        
                        $body = "<h2 style='color:#1f2937; margin-top:0;'>Welcome to {$appName}</h2>";
                        $body .= "<p>Hello {$data['name']},</p>";
                        $body .= "<p>An agency portal account has been created for you. Before you can log in, you must set up a secure password for your account.</p>";
                        $body .= "<p style='text-align: center; margin: 30px 0;'><a href='{$resetLink}' style='display:inline-block; padding:12px 24px; background-color:#1c70b4; color:#ffffff; text-decoration:none; border-radius:6px; font-weight:bold;'>Set Your Password</a></p>";
                        $body .= "<p>If the button above does not work, copy and paste the following link into your browser:</p>";
                        $body .= "<p style='word-break: break-all; color: #6b7280; font-size: 14px;'>{$resetLink}</p>";

                        sendEmail($data['email'], "Welcome! Please set your password", $body);

                        systemLog('PARTNER_AND_USER_CREATED', "Admin created a new partner agency and user account: {$data['name']}");
                        flash('system_msg', 'Partner agency and user account added successfully! A welcome email has been sent.', 'success');
                        
                        header('Location: ' . URLROOT . '/admin/partners');
                        exit;
                    }
                } else {
                    flash('system_msg', 'Failed to create partner agency record.', 'error');
                    $this->view('admin/partners/add', $data);
                }
            } else {
                $this->view('admin/partners/add', $data);
            }
        } else {
            $data = [
                'name' => '', 'email' => '', 'password' => '', 'contact_number' => '', 
                'address_street' => '', 'address_suburb' => '', 'address_city' => '', 'address_state' => '', 'address_zip' => '', 'address_country' => '',
                'jobcard_prefix' => 'PRT-', 'jobcard_sequence' => 1, 'logo' => '',
                'name_err' => '', 'email_err' => '', 'password_err' => ''
            ];
            $this->view('admin/partners/add', $data);
        }
    }

    public function editPartner($id = null): void {
        if (!$id) { header('Location: ' . URLROOT . '/admin/partners'); exit; }
        
        $partner = $this->partnerModel->getPartnerById((int)$id);
        if (!$partner) { header('Location: ' . URLROOT . '/admin/partners'); exit; }

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            
            $data = [
                'id' => (int)$id,
                'partner' => $partner,
                'name' => trim($_POST['name']),
                'email' => trim($_POST['email'] ?? ''),
                'contact_number' => trim($_POST['contact_number'] ?? ''),
                'address_street' => trim($_POST['address_street'] ?? ''),
                'address_suburb' => trim($_POST['address_suburb'] ?? ''),
                'address_city' => trim($_POST['address_city'] ?? ''),
                'address_state' => trim($_POST['address_state'] ?? ''),
                'address_zip' => trim($_POST['address_zip'] ?? ''),
                'address_country' => trim($_POST['address_country'] ?? ''),
                'jobcard_prefix' => trim($_POST['jobcard_prefix'] ?? ''),
                'jobcard_sequence' => empty($_POST['jobcard_sequence']) ? 1 : (int)$_POST['jobcard_sequence'],
                'logo' => $partner->logo, // Keep existing logo unless changed
                'name_err' => ''
            ];

            if (empty($data['name'])) {
                $data['name_err'] = 'Please enter a partner name.';
            }

            // --- FILE UPLOAD LOGIC FOR LOGO ---
            if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === 0) {
                $uploadDir = '../public/uploads/';
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                $fileType = mime_content_type($_FILES['logo']['tmp_name']);
                
                if (in_array($fileType, $allowedTypes)) {
                    $ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                    $filename = 'partner_' . time() . '.' . $ext;
                    if (move_uploaded_file($_FILES['logo']['tmp_name'], $uploadDir . $filename)) {
                        $data['logo'] = $filename; // Override with new logo
                    }
                }
            }

            if (empty($data['name_err'])) {
                if ($this->partnerModel->updatePartner($data)) {
                    systemLog('PARTNER_UPDATED', "Admin updated partner agency: {$data['name']}");
                    flash('system_msg', 'Partner updated successfully.', 'success');
                    header('Location: ' . URLROOT . '/admin/partners');
                    exit;
                }
            } else {
                $this->view('admin/partners/edit', $data);
            }
        } else {
            $data = ['partner' => $partner, 'name_err' => ''];
            $this->view('admin/partners/edit', $data);
        }
    }

    public function deletePartner($id = null): void {
        if ($_SERVER['REQUEST_METHOD'] == 'POST' && $id) {
            $partnerId = (int)$id;

            if ($this->partnerModel->deletePartner($partnerId)) {
                systemLog('PARTNER_DELETED', "Admin deleted a partner agency (ID: {$partnerId}).");
                flash('system_msg', 'Partner permanently deleted.', 'success');
            } else {
                flash('system_msg', 'Something went wrong while deleting the partner.', 'error');
            }
        }

        header('Location: ' . URLROOT . '/admin/partners');
        exit;
    }
}