<?php

namespace App\Controllers;

use App\Utils\Auth;
use App\Utils\Flash;
use App\Config\Database;

class BranchController {

    public function index() {
        Auth::requireAdmin();
        $user = Auth::user();
        
        $db = Database::getInstance()->getConnection();
        // Pagination
        $perPage = 20;
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        
        $countStmt = $db->prepare("SELECT COUNT(*) FROM branches WHERE tenant_id = ?");
        $countStmt->execute([$user['tenant_id']]);
        $totalItems = $countStmt->fetchColumn();
        
        $totalPages = max(1, ceil($totalItems / $perPage));
        if ($page > $totalPages) $page = $totalPages;
        $offset = ($page - 1) * $perPage;

        $stmt = $db->prepare("SELECT * FROM branches WHERE tenant_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?");
        $stmt->execute([$user['tenant_id'], $perPage, $offset]);
        $branches = $stmt->fetchAll();

        require_once __DIR__ . '/../../views/admin/branches/index.php';
    }

    public function create() {
        Auth::requireAdmin();
        require_once __DIR__ . '/../../views/admin/branches/create.php';
    }

    public function store() {
        Auth::requireAdmin();
        $user = Auth::user();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: /branches");
            exit;
        }

        $name = $_POST['name'] ?? '';
        $address = $_POST['address'] ?? '';
        $phone = $_POST['phone'] ?? '';

        if (empty($name)) {
            Flash::set('error', 'Branch name is required.');
            header("Location: /branches/create");
            exit;
        }

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("INSERT INTO branches (tenant_id, name, address, phone) VALUES (?, ?, ?, ?)");
        $stmt->execute([$user['tenant_id'], $name, $address, $phone]);

        Flash::set('success', 'Branch created successfully.');
        header("Location: /branches");
        exit;
    }

    public function edit($id) {
        Auth::requireAdmin();
        $user = Auth::user();

        $db = Database::getInstance()->getConnection();
        $stmt = $db->prepare("SELECT * FROM branches WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $user['tenant_id']]);
        $branch = $stmt->fetch();

        if (!$branch) {
            Flash::set('error', 'Branch not found.');
            header("Location: /branches");
            exit;
        }

        require_once __DIR__ . '/../../views/admin/branches/edit.php';
    }

    public function update($id) {
        Auth::requireAdmin();
        $user = Auth::user();

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header("Location: /branches");
            exit;
        }

        $name = $_POST['name'] ?? '';
        $address = $_POST['address'] ?? '';
        $phone = $_POST['phone'] ?? '';

        if (empty($name)) {
            Flash::set('error', 'Branch name is required.');
            header("Location: /branches/edit/$id");
            exit;
        }

        $db = Database::getInstance()->getConnection();
        
        // Verify ownership
        $stmt = $db->prepare("SELECT id FROM branches WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $user['tenant_id']]);
        if (!$stmt->fetch()) {
            Flash::set('error', 'Branch not found or permission denied.');
            header("Location: /branches");
            exit;
        }

        $stmt = $db->prepare("UPDATE branches SET name = ?, address = ?, phone = ? WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$name, $address, $phone, $id, $user['tenant_id']]);

        Flash::set('success', 'Branch updated successfully.');
        header("Location: /branches");
        exit;
    }

    public function destroy($id) {
        Auth::requireAdmin();
        $user = Auth::user();

        $db = Database::getInstance()->getConnection();

        // Check if it's the main branch or something we shouldn't delete (optional logic)
        $stmt = $db->prepare("SELECT name FROM branches WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $user['tenant_id']]);
        $branch = $stmt->fetch();

        if (!$branch) {
            Flash::set('error', 'Branch not found.');
            header("Location: /branches");
            exit;
        }
        
        if ($branch['name'] === 'Main Branch') {
            Flash::set('error', 'Cannot delete the Main Branch.');
            header("Location: /branches");
            exit;
        }

        $stmt = $db->prepare("DELETE FROM branches WHERE id = ? AND tenant_id = ?");
        $stmt->execute([$id, $user['tenant_id']]);

        Flash::set('success', 'Branch deleted successfully.');
        header("Location: /branches");
        exit;
    }
}
