<?php

class CustomerController extends Controller {

    public function index() {
        if (session_status() === PHP_SESSION_NONE) session_start();

        if (!isset($_SESSION['user_id'])) {
            header("Location: " . BASE_URL . "/login");
            exit;
        }

        $userId = $_SESSION['user_id'];
        $role = $_SESSION['user_role'];
        $limit = 10;
        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
        $offset = ($page - 1) * $limit;

        $customerModel = $this->model('Customer');
        $customers = $customerModel->getCustomersPaginated($userId, $role, $limit, $offset);
        $totalCustomers = $customerModel->countCustomers($userId, $role);
        $totalPages = ceil($totalCustomers / $limit);

        $this->view('customers/index', [
            'customers' => $customers,
            'role' => $role,
            'currentPage' => $page,
            'totalPages' => $totalPages
        ]);
    }

    public function add() {
    if (session_status() === PHP_SESSION_NONE) session_start();

    if (!isset($_SESSION['user_id'])) {
        header("Location: " . BASE_URL . "/login");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = [
            'user_id' => $_SESSION['user_id'],
            'name' => trim($_POST['name']),
            'email' => trim($_POST['email']),
            'phone' => trim($_POST['phone']),
            'company' => trim($_POST['company']),
            'address_1' => trim($_POST['address_1']),
            'address_2' => trim($_POST['address_2']),
            'city' => trim($_POST['city']),
            'country' => trim($_POST['country']),
            'postcode' => trim($_POST['postcode']),
            'unit_number' => trim($_POST['unit_number']),
        ];

        $customerModel = $this->model('Customer');
        if ($customerModel->addCustomer($data)) {
            $_SESSION['success'] = "Customer added successfully.";
            header("Location: " . BASE_URL . "/customer");
            exit;
        } else {
            $_SESSION['error'] = "Failed to add customer.";
        }
    }

    $this->view('customers/add');
}

public function edit($id = null) {
    if (session_status() === PHP_SESSION_NONE) session_start();

    if (!isset($_SESSION['user_id']) || !$id) {
        header("Location: " . BASE_URL . "/login");
        exit;
    }

    $customerModel = $this->model('Customer');
    $customer = $customerModel->getCustomerById($id);

    if (!$customer) {
        $_SESSION['error'] = "Customer not found.";
        header("Location: " . BASE_URL . "/customer");
        exit;
    }

    if (strtolower($_SESSION['user_role']) !== 'admin' && $customer['user_id'] != $_SESSION['user_id']) {
        $_SESSION['error'] = "You do not have permission to edit this customer.";
        header("Location: " . BASE_URL . "/customer");
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $data = [
            'name' => trim($_POST['name']),
            'email' => trim($_POST['email']),
            'phone' => trim($_POST['phone']),
            'company' => trim($_POST['company']),
            'address_1' => trim($_POST['address_1']),
            'address_2' => trim($_POST['address_2']),
            'city' => trim($_POST['city']),
            'country' => trim($_POST['country']),
            'postcode' => trim($_POST['postcode']),
            'unit_number' => trim($_POST['unit_number']),
        ];

        if ($customerModel->updateCustomer($id, $data)) {
            $_SESSION['success'] = "Customer updated successfully.";
            header("Location: " . BASE_URL . "/customer");
            exit;
        } else {
            $_SESSION['error'] = "Failed to update customer.";
        }
    }

    $this->view('customers/edit', ['customer' => $customer]);
}


    public function delete($id = null) {
        if (session_status() === PHP_SESSION_NONE) session_start();

        if (!isset($_SESSION['user_id']) || !$id) {
            header("Location: " . BASE_URL . "/login");
            exit;
        }

        $customerModel = $this->model('Customer');
        $customer = $customerModel->getCustomerById($id);

        if (!$customer) {
            $_SESSION['error'] = "Customer not found.";
            header("Location: " . BASE_URL . "/customer");
            exit;
        }

        if (strtolower($_SESSION['user_role']) !== 'admin' && $customer['user_id'] != $_SESSION['user_id']) {
            $_SESSION['error'] = "You do not have permission to delete this customer.";
            header("Location: " . BASE_URL . "/customer");
            exit;
        }

        if ($customerModel->deleteCustomer($id)) {
            $_SESSION['success'] = "Customer deleted successfully.";
        } else {
            $_SESSION['error'] = "Failed to delete customer.";
        }

        header("Location: " . BASE_URL . "/customer");
        exit;
    }
}
