<?php 
include 'dbconnt.php'; 
function Querydb($query) {
    GLOBAL $conn;
    return mysqli_query($conn, $query);
}
function getUserId($user_id) {
    $sql = Querydb("SELECT * FROM users WHERE user_id = '$user_id' ");
    return mysqli_fetch_assoc($sql);
}
function is_page_active($page_name) {
    $current_uri = $_SERVER['REQUEST_URI'];
    $path = parse_url($current_uri, PHP_URL_PATH);
    $current_file = basename($path);
    if ($current_file === '') {
        $current_file = 'index.php';
    }
    if ($current_file === $page_name) {
        return 'active';
    }
    return '';
}

/**
 * Fetches Trip, Truck, and Driver details for a specific ATC and Business
 */
function getTripByAtcAndBusiness($atc_id, $business_id) {
    $sql = "SELECT 
                t.trip_id AS trip_id,
                t.status AS trip_status,
                tr.license_plate,
                tr.model AS truck_model,
                d.first_name,
                d.last_name,
                d.license_number AS driver_license,
                CONCAT(d.first_name, ' ', d.last_name) AS driver_name
            FROM trips t
            INNER JOIN trucks tr ON t.truck_id = tr.truck_id
            INNER JOIN drivers d ON t.driver_id = d.driver_id
            WHERE t.atc_id = '$atc_id' 
            AND t.business_id = '$business_id' 
            LIMIT 1";

    $stm = Querydb($sql);
    return $stmt = mysqli_fetch_assoc($stm);
}

function check_page_access($page_path = null) {
    if (!isset($_SESSION['user_id'])) {
        header('Location: ../auth-login.html');
        exit;
    }
    $user_id = $_SESSION['user_id'];
    $user = getUserId($user_id);
    // Determine current page if not provided
    if ($page_path === null) {
        $current_uri = $_SERVER['REQUEST_URI'];
        $path = parse_url($current_uri, PHP_URL_PATH);
        $page = basename($path);
    } else {
        $page = basename($page_path);
    }

    if (!can_user_access($user_id, $page)) {
        header('Location: no_access.php');
        exit;
    }
}

function can_user_access($user_id, $page) {
    if (!$user_id) return false;
    if (isset($_SESSION['user_type'])) {
        $type = strtolower($_SESSION['user_type']);
        if ($type === 'admin' || $type === 'manager') return true;
    }
    $page_clean = trim($page);
    $page_clean = ltrim($page_clean, '/');
    $q = Querydb("SELECT page, allowed FROM user_page_permissions WHERE user_id = $user_id LIMIT 1");    
    if ($q && mysqli_num_rows($q) > 0) {
        $r = mysqli_fetch_assoc($q);
        if ((int)$r['allowed'] === 1) {
            $pg_string = $r['page']; 
            $allowed_pages_array = explode(',', $pg_string);
            $trimmed_pages = array_map('trim', $allowed_pages_array);
            if (in_array($page_clean, $trimmed_pages, true)) {
                return true;
            }
        }
    }
    return false;
}

function generateSerialOrderId() {
    // 1. Get the last ID based on the primary key (id)
    $business_id = $_SESSION['business_id'];
    $sql = "SELECT id FROM orders WHERE business_id = '$business_id' ORDER BY id DESC LIMIT 1";
    $result = Querydb($sql);
    
    if (mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        // Extract numbers from the string (e.g., "ORD-0005" becomes 5)
        $last_number = preg_replace('/[^0-9]/', '', $row['id']);
        $next_number = intval($last_number) + 1;
    } else {
        // First order in the system
        $next_number = 1;
    }

    // 2. Format with a prefix and leading zeros (4 digits)
    return "ORD-".date('y|'). str_pad($next_number, 10, "0", STR_PAD_LEFT);
}

function generateSerialTransId() {
    $business_id = $_SESSION['business_id'];
    // 1. Get the last transaction ID
    $sql = "SELECT trans_id FROM transactions WHERE business_id = '$business_id' ORDER BY transaction_id DESC LIMIT 1";
    $result =Querydb($sql);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        // Extract numbers from the string (e.g., "TRN-0005" becomes 5)
        $last_number = preg_replace('/[^0-9]/', '', $row['trans_id']);
        $next_number = intval($last_number) + 1;
    } else {
        // First transaction in the system
        $next_number = 1;
    }

    // 2. Format with "TRN-" and pad with 4 zeros
    return "TRN-" . str_pad($next_number, 10, "0", STR_PAD_LEFT);
}

function get_avatar($name, $bg = '0d6efd', $color = 'fff') {
    // 1. URL encode the name to handle spaces and special characters
    $encoded_name = urlencode($name);
    
    // 2. Return the formatted URL
    return "https://ui-avatars.com/api/?name={$encoded_name}&background={$bg}&color={$color}&size=128";
}

if (isset($_GET['customer_id']) && isset($_GET['format'])) {
    $cid = $_GET['customer_id'];
    $from =$_GET['start_date'];
    $to =$_GET['end_date'];
    $format = $_GET['format'] ?? 'csv';
    $business_id = $_SESSION['business_id'];
    $query = "SELECT created_at, description, type, amount, reference_no, trans_id, bal_after FROM transactions WHERE business_id = '$business_id' AND customer_id = '$cid' AND DATE(created_at) BETWEEN '$from' AND '$to' ORDER BY created_at ASC";
    $result = Querydb($query);

    // // Fetch Customer Info
    $cust_res = Querydb("SELECT name FROM customers WHERE business_id = '$business_id' AND customer_id = '$cid'");
    $cust = mysqli_fetch_assoc($cust_res);
    $customer_name = $cust['name'] ?? 'Customer';

    if ($format == 'csv') {
        // --- CSV EXPORT LOGIC ---
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="Statement_'.$customer_name.'.csv"');
        $output = fopen('php://output', 'w');
        // Output the column headings
        fputcsv($output, array('Date', 'Transactions ID', 'Description', 'Type', 'Debit', 'Credit', 'Balance', 'Reference'));
        while ($row = mysqli_fetch_assoc($result)) {
            $date = date('d-M-Y', strtotime($row['created_at']));
            $desc = $row['description'];
            $type = $row['type'];
            $amt = number_format($row['amount'], 2);
            $trans = $row['trans_id'];
            $bal = number_format($row['bal_after'], 2);
            
            // Split amount into Debit or Credit columns
            $debit = ($type == 'debit') ? $amt : 0;
            $credit = ($type == 'credit') ? $amt : 0;

            fputcsv($output, array($date, $trans, $desc, $type, $debit, $credit, $bal, $row['reference_no']));
        }
        
        fclose($output);
        exit;
    } else {
        // --- PDF / PRINT LOGIC ---
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>Statement - <?php echo $customer_name; ?></title>
            <link rel="stylesheet" href="assets/css/bootstrap.css">
            <style>
                @media print { .no-print { display: none; } }
                .invoice-box { max-width: 800px; padding: 30px; border: 1px solid #eee; }
            </style>
        </head>
        <body onload="window.print()">
            <div class="invoice-box bg-white shadow-sm mt-5">
                <div class="d-flex justify-content-between mb-4">
                    <div>
                        <h2 class="fw-bold text-uppercase">Statement of Account</h2>
                        <p>Customer: <strong><?php echo $customer_name; ?></strong><br>
                        Period: <?php echo "$from to $to"; ?></p>
                    </div>
                    <div class="text-end">
                        <button class="btn btn-sm btn-secondary no-print" onclick="window.print()">Print PDF</button>
                    </div>
                </div>
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Transaction ID</th>
                            <th>Description</th>
                            <th>Type</th>
                            <th>Debit</th>
                            <th>Credit</th>
                            <th>Balance</th>
                            <th>Refe</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        while ($row = $result->fetch_assoc()) {
                            $date = date('d-M-Y', strtotime($row['created_at']));
                            $desc = $row['description'];
                            $type = $row['type'];
                            $amt = abs((float)$row['amount']);
                            $trans = $row['trans_id'];
                            $bal = $row['bal_after'];
                            
                            // Split amount into Debit or Credit columns
                            $debit = ($type == 'debit') ? $amt : 0;
                            $credit = ($type == 'credit') ? $amt : 0; ?>
                        <tr>
                            <td><?php echo $date; ?></td>
                            <td><?php echo $trans; ?></td>
                            <td><?php echo $desc; ?></td>
                            <td><?php echo ($row['type']=='credit') ? 'Credit' : 'Debit'; ?></td>
                            <td class="<?php echo ($row['type']=='debit') ? 'text-danger' : 'text-black'; ?>">
                                ₦ <?php echo number_format($debit, 2); ?>
                            </td>
                            <td class="<?php echo ($row['type']=='credit') ? 'text-success' : 'text-black'; ?>">
                                ₦ <?php echo number_format($credit, 2); ?>
                            </td>
                            <td>₦<?php echo number_format($bal, 2); ?></td>
                            <td><?php echo $row['reference_no']; ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}





 ?>