<?php
// Include config file
require_once "includes/config.php";
require_once "includes/session.php";

// Check if the user is logged in
checkLogin();

// Process form submission for Ljubo tab
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["ljubo_submit"])) {
    $date = $_POST["date"];
    $euro_plus = !empty($_POST["euro_plus"]) ? $_POST["euro_plus"] : 0;
    $euro_minus = !empty($_POST["euro_minus"]) ? $_POST["euro_minus"] : 0;
    $rsd_plus = !empty($_POST["rsd_plus"]) ? $_POST["rsd_plus"] : 0;
    $rsd_minus = !empty($_POST["rsd_minus"]) ? $_POST["rsd_minus"] : 0;
    $comment = $_POST["comment"];
    
    // Calculate new totals based on previous values and changes
    $total = calculateNewTotal("ljubo_entries", $euro_plus, $euro_minus);
    $rsd_total = calculateNewRsdTotal("ljubo_entries", $rsd_plus, $rsd_minus);
    
    $sql = "INSERT INTO ljubo_entries (date, total, euro_plus, euro_minus, rsd_total, rsd_plus, rsd_minus, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
    if ($stmt = mysqli_prepare($conn, $sql)) {
        mysqli_stmt_bind_param($stmt, "sdddddds", $date, $total, $euro_plus, $euro_minus, $rsd_total, $rsd_plus, $rsd_minus, $comment);
        
        if (mysqli_stmt_execute($stmt)) {
            // Redirect to page 1 after adding a new entry (newest data is on page 1)
            header("location: index.php?tab=ljubo&ljubo_page=1&success=1");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
        
        mysqli_stmt_close($stmt);
    }
}

// Process form submission for Maja tab
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["maja_submit"])) {
    $date = $_POST["date"];
    $euro_plus = !empty($_POST["euro_plus"]) ? $_POST["euro_plus"] : 0;
    $euro_minus = !empty($_POST["euro_minus"]) ? $_POST["euro_minus"] : 0;
    $rsd_plus = !empty($_POST["rsd_plus"]) ? $_POST["rsd_plus"] : 0;
    $rsd_minus = !empty($_POST["rsd_minus"]) ? $_POST["rsd_minus"] : 0;
    $comment = $_POST["comment"];
    
    // Calculate new totals based on previous values and changes
    $total = calculateNewTotal("maja_entries", $euro_plus, $euro_minus);
    $rsd_total = calculateNewRsdTotal("maja_entries", $rsd_plus, $rsd_minus);
    
    $sql = "INSERT INTO maja_entries (date, total, euro_plus, euro_minus, rsd_total, rsd_plus, rsd_minus, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    
    if ($stmt = mysqli_prepare($conn, $sql)) {
        mysqli_stmt_bind_param($stmt, "sdddddds", $date, $total, $euro_plus, $euro_minus, $rsd_total, $rsd_plus, $rsd_minus, $comment);
        
        if (mysqli_stmt_execute($stmt)) {
            // Redirect to page 1 after adding a new entry (newest data is on page 1)
            header("location: index.php?tab=maja&maja_page=1&success=1");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
        
        mysqli_stmt_close($stmt);
    }
}

// Process delete operation
if (isset($_GET["action"]) && $_GET["action"] == "delete") {
    $id = $_GET["id"];
    $tab = $_GET["tab"];
    
    $table = ($tab == "ljubo") ? "ljubo_entries" : "maja_entries";
    
    $sql = "DELETE FROM $table WHERE id = ?";
    
    if ($stmt = mysqli_prepare($conn, $sql)) {
        mysqli_stmt_bind_param($stmt, "i", $id);
        
        if (mysqli_stmt_execute($stmt)) {
            // After deleting, calculate the appropriate page to redirect to
            $count_sql = "SELECT COUNT(*) as total FROM $table";
            $count_result = mysqli_query($conn, $count_sql);
            $total_rows = mysqli_fetch_assoc($count_result)['total'];
            $total_pages = ceil($total_rows / 5);
            
            // Get the current page from GET parameters
            $current_page = ($tab == "ljubo") ? 
                (isset($_GET["ljubo_page"]) ? intval($_GET["ljubo_page"]) : 1) : 
                (isset($_GET["maja_page"]) ? intval($_GET["maja_page"]) : 1);
            
            // Ensure we don't redirect to a page that doesn't exist anymore
            $page_param = ($tab == "ljubo") ? "ljubo_page" : "maja_page";
            $redirect_page = min($current_page, $total_pages);
            $redirect_page = max(1, $redirect_page); // Ensure at least page 1
            
            header("location: index.php?tab=$tab&{$page_param}=1&deleted=1");
            exit;
        } else {
            echo "Error: " . mysqli_error($conn);
        }
        
        mysqli_stmt_close($stmt);
    }
}

// Get active tab
$active_tab = isset($_GET["tab"]) ? $_GET["tab"] : "ljubo";

// Pagination settings
$rows_per_page = 5;

// Fetch Ljubo entries with pagination
$ljubo_entries = [];
$ljubo_count_sql = "SELECT COUNT(*) as total FROM ljubo_entries";
$ljubo_count_result = mysqli_query($conn, $ljubo_count_sql);
$ljubo_total_rows = mysqli_fetch_assoc($ljubo_count_result)['total'];
$ljubo_total_pages = ceil($ljubo_total_rows / $rows_per_page);

// Default to page 1 for Ljubo (newest data is on page 1)
$ljubo_page = isset($_GET["ljubo_page"]) ? intval($_GET["ljubo_page"]) : 1;
// Ensure page is valid
$ljubo_page = max(1, min($ljubo_page, $ljubo_total_pages));
$ljubo_offset = max(0, ($ljubo_page - 1) * $rows_per_page);

// Get entries with newest first
$sql = "SELECT * FROM ljubo_entries ORDER BY date DESC, id DESC LIMIT $ljubo_offset, $rows_per_page";
$result = mysqli_query($conn, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $ljubo_entries[] = $row;
    }
}

// Fetch all Ljubo entries for totals calculation
$all_ljubo_entries = [];
$sql = "SELECT * FROM ljubo_entries ORDER BY date DESC, id DESC";
$result = mysqli_query($conn, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $all_ljubo_entries[] = $row;
    }
}

// Fetch Maja entries with pagination
$maja_entries = [];
$maja_count_sql = "SELECT COUNT(*) as total FROM maja_entries";
$maja_count_result = mysqli_query($conn, $maja_count_sql);
$maja_total_rows = mysqli_fetch_assoc($maja_count_result)['total'];
$maja_total_pages = ceil($maja_total_rows / $rows_per_page);

// Default to page 1 for Maja (newest data is on page 1)
$maja_page = isset($_GET["maja_page"]) ? intval($_GET["maja_page"]) : 1;
// Ensure page is valid
$maja_page = max(1, min($maja_page, $maja_total_pages));
$maja_offset = max(0, ($maja_page - 1) * $rows_per_page);

// Get entries with newest first
$sql = "SELECT * FROM maja_entries ORDER BY date DESC, id DESC LIMIT $maja_offset, $rows_per_page";
$result = mysqli_query($conn, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $maja_entries[] = $row;
    }
}

// Fetch all Maja entries for totals calculation
$all_maja_entries = [];
$sql = "SELECT * FROM maja_entries ORDER BY date DESC, id DESC";
$result = mysqli_query($conn, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $all_maja_entries[] = $row;
    }
}

// Get last totals
$ljubo_total = getLastTotal("ljubo_entries");
$maja_total = getLastTotal("maja_entries");
$grand_total = $ljubo_total + $maja_total;

// Get last RSD totals
$ljubo_rsd_total = getLastRsdTotal("ljubo_entries");
$maja_rsd_total = getLastRsdTotal("maja_entries");
$grand_rsd_total = $ljubo_rsd_total + $maja_rsd_total;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Stednja</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f8f9fa;
            padding: 20px;
        }
        .wrapper {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        .nav-tabs .nav-link {
            font-weight: bold;
            color: #495057;
        }
        .nav-tabs .nav-link.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        .table th {
            background-color: #f8f9fa;
        }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .action-buttons a {
            padding: 2px 8px;
        }
        .total-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 5px rgba(0,0,0,0.05);
        }
        .total-card .total-amount {
            font-size: 24px;
            font-weight: bold;
            margin-top: 10px;
        }
        .form-container {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        /* Custom styling for date inputs to show in DD/MM/YYYY format */
        input[type="date"] {
            position: relative;
        }
        
        input[type="date"]::-webkit-calendar-picker-indicator {
            position: absolute;
            right: 10px;
            top: 10px;
        }
        
        .date-format-label {
            display: block;
            font-size: 12px;
            color: #6c757d;
            margin-top: 2px;
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="header">
            <h2>Štednja Aplikacija</h2>
            <div>
                <span class="mr-3">Dobrodosao, <?php echo htmlspecialchars($_SESSION["username"]); ?></span>
                <?php if ($_SESSION["role"] == "admin") { ?>
                    <a href="admin/index.php" class="btn btn-info btn-sm">Admin Panel</a>
                <?php } ?>
                <a href="https://ljubomirlukic.com" class="btn btn-info btn-sm" target="_blank">Homepage</a>
                <a href="logout.php" class="btn btn-danger btn-sm">Izloguj se</a>
            </div>
        </div>
        
        <ul class="nav nav-tabs mb-4">
            <li class="nav-item">
                <a class="nav-link <?php echo $active_tab == 'ljubo' ? 'active' : ''; ?>" href="index.php?tab=ljubo">LJUBO</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $active_tab == 'maja' ? 'active' : ''; ?>" href="index.php?tab=maja">MAJA</a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?php echo $active_tab == 'total' ? 'active' : ''; ?>" href="index.php?tab=total">UKUPNO</a>
            </li>
        </ul>
        
        <?php if (isset($_GET["success"])) { ?>
            <div class="alert alert-success">Unos uspesno snimljen!</div>
        <?php } ?>
        
        <?php if (isset($_GET["deleted"])) { ?>
            <div class="alert alert-success">Zapis uspesno obrisan!</div>
        <?php } ?>
        
        <?php if (isset($_GET["updated"])) { ?>
            <div class="alert alert-success">Unos uspesno azuriran!</div>
        <?php } ?>
        
        <!-- LJUBO Tab -->
        <div class="tab-content <?php echo $active_tab == 'ljubo' ? 'd-block' : 'd-none'; ?>">
            <div class="form-container">
                <h4>Dodaj novi unos</h4>
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                    <div class="form-row">
                        <div class="form-group col-md-2">
                            <label>Datum</label>
                            <input type="date" name="date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                        </div>
                        <div class="form-group col-md-2">
                            <label>Euro +</label>
                            <input type="number" name="euro_plus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>Euro -</label>
                            <input type="number" name="euro_minus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>RSD +</label>
                            <input type="number" name="rsd_plus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>RSD -</label>
                            <input type="number" name="rsd_minus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-10">
                            <label>Komentar</label>
                            <input type="text" name="comment" class="form-control" required>
                        </div>
                        <div class="form-group col-md-2 d-flex align-items-end">
                            <button type="submit" name="ljubo_submit" class="btn btn-primary btn-block">Dodaj</button>
                        </div>
                    </div>
                </form>
            </div>
            
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Euro ukupno</th>
                        <th>Euro +</th>
                        <th>Euro -</th>
                        <th>RSD ukupno</th>
                        <th>RSD +</th>
                        <th>RSD -</th>
                        <th>Komentar</th>
                        <th>Operacije</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($ljubo_entries as $entry) { ?>
                        <tr>
                            <td><?php echo formatDate($entry["date"]); ?></td>
                            <td><strong class="text-danger"><?php echo htmlspecialchars($entry["total"]); ?></strong></td>
                            <td><?php echo htmlspecialchars($entry["euro_plus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["euro_minus"]); ?></td>
                            <td><strong class="text-success"><?php echo htmlspecialchars($entry["rsd_total"]); ?></strong></td>
                            <td><?php echo htmlspecialchars($entry["rsd_plus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["rsd_minus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["comment"]); ?></td>
                            <td class="action-buttons">
                                <a href="edit.php?id=<?php echo $entry["id"]; ?>&tab=ljubo" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                <a href="index.php?action=delete&id=<?php echo $entry["id"]; ?>&tab=ljubo" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this entry?');"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    <?php } ?>
                    <?php if (empty($ljubo_entries)) { ?>
                        <tr>
                            <td colspan="9" class="text-center">No entries found</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
            
            <!-- Ljubo Pagination -->
            <?php if ($ljubo_total_pages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo ($ljubo_page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=ljubo&ljubo_page=1" aria-label="First">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item <?php echo ($ljubo_page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=ljubo&ljubo_page=<?php echo $ljubo_page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    
                    <?php
                    // Show a range of page numbers
                    $start_page = max(1, $ljubo_page - 2);
                    $end_page = min($ljubo_total_pages, $ljubo_page + 2);
                    
                    for ($i = $start_page; $i <= $end_page; $i++): ?>
                        <li class="page-item <?php echo ($i == $ljubo_page) ? 'active' : ''; ?>">
                            <a class="page-link" href="index.php?tab=ljubo&ljubo_page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    
                    <li class="page-item <?php echo ($ljubo_page >= $ljubo_total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=ljubo&ljubo_page=<?php echo $ljubo_page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li class="page-item <?php echo ($ljubo_page >= $ljubo_total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=ljubo&ljubo_page=<?php echo $ljubo_total_pages; ?>" aria-label="Last">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
        
        <!-- MAJA Tab -->
        <div class="tab-content <?php echo $active_tab == 'maja' ? 'd-block' : 'd-none'; ?>">
            <div class="form-container">
                <h4>Dodaj novi unos</h4>
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                    <div class="form-row">
                        <div class="form-group col-md-2">
                            <label>Datum</label>
                            <input type="date" name="date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                        </div>
                        <div class="form-group col-md-2">
                            <label>Euro +</label>
                            <input type="number" name="euro_plus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>Euro -</label>
                            <input type="number" name="euro_minus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>RSD +</label>
                            <input type="number" name="rsd_plus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                        <div class="form-group col-md-2">
                            <label>RSD -</label>
                            <input type="number" name="rsd_minus" class="form-control" required step="0.01" value="0" placeholder="0">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-10">
                            <label>Komentar</label>
                            <input type="text" name="comment" class="form-control" required>
                        </div>
                        <div class="form-group col-md-2 d-flex align-items-end">
                            <button type="submit" name="maja_submit" class="btn btn-primary btn-block">Dodaj</button>
                        </div>
                    </div>
                </form>
            </div>
            
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>Datum</th>
                        <th>Euro ukupno</th>
                        <th>Euro +</th>
                        <th>Euro -</th>
                        <th>RSD ukupno</th>
                        <th>RSD +</th>
                        <th>RSD -</th>
                        <th>Komentar</th>
                        <th>Operacije</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($maja_entries as $entry) { ?>
                        <tr>
                            <td><?php echo formatDate($entry["date"]); ?></td>
                            <td><strong class="text-danger"><?php echo htmlspecialchars($entry["total"]); ?></strong></td>
                            <td><?php echo htmlspecialchars($entry["euro_plus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["euro_minus"]); ?></td>
                            <td><strong class="text-success"><?php echo htmlspecialchars($entry["rsd_total"]); ?></strong></td>
                            <td><?php echo htmlspecialchars($entry["rsd_plus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["rsd_minus"]); ?></td>
                            <td><?php echo htmlspecialchars($entry["comment"]); ?></td>
                            <td class="action-buttons">
                                <a href="edit.php?id=<?php echo $entry["id"]; ?>&tab=maja" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                <a href="index.php?action=delete&id=<?php echo $entry["id"]; ?>&tab=maja" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this entry?');"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                    <?php } ?>
                    <?php if (empty($maja_entries)) { ?>
                        <tr>
                            <td colspan="9" class="text-center">No entries found</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
            
            <!-- Maja Pagination -->
            <?php if ($maja_total_pages > 1): ?>
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo ($maja_page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=maja&maja_page=1" aria-label="First">
                            <span aria-hidden="true">&laquo;&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item <?php echo ($maja_page <= 1) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=maja&maja_page=<?php echo $maja_page - 1; ?>" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    
                    <?php
                    // Show a range of page numbers
                    $start_page = max(1, $maja_page - 2);
                    $end_page = min($maja_total_pages, $maja_page + 2);
                    
                    for ($i = $start_page; $i <= $end_page; $i++): ?>
                        <li class="page-item <?php echo ($i == $maja_page) ? 'active' : ''; ?>">
                            <a class="page-link" href="index.php?tab=maja&maja_page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    
                    <li class="page-item <?php echo ($maja_page >= $maja_total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=maja&maja_page=<?php echo $maja_page + 1; ?>" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                    <li class="page-item <?php echo ($maja_page >= $maja_total_pages) ? 'disabled' : ''; ?>">
                        <a class="page-link" href="index.php?tab=maja&maja_page=<?php echo $maja_total_pages; ?>" aria-label="Last">
                            <span aria-hidden="true">&raquo;&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
        
        <!-- TOTAL Tab -->
        <div class="tab-content <?php echo $active_tab == 'total' ? 'd-block' : 'd-none'; ?>">
            <div class="row">
                <div class="col-md-4">
                    <div class="total-card">
                        <h5>LJUBOMIR Ukupno</h5>
                        <div class="total-amount"><?php echo number_format($ljubo_total, 2); ?> €</div>
                        <div class="total-amount" style="font-size: 18px;"><?php echo number_format($ljubo_rsd_total, 2); ?> RSD</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="total-card">
                        <h5>MAJA Ukupno</h5>
                        <div class="total-amount"><?php echo number_format($maja_total, 2); ?> €</div>
                        <div class="total-amount" style="font-size: 18px;"><?php echo number_format($maja_rsd_total, 2); ?> RSD</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="total-card" style="background-color: #e9f7fe;">
                        <h5>TOTAL</h5>
                        <div class="total-amount" style="color: #0056b3;"><?php echo number_format($grand_total, 2); ?> €</div>
                        <div class="total-amount" style="color: #0056b3; font-size: 18px;"><?php echo number_format($grand_rsd_total, 2); ?> RSD</div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <div class="col-md-12 text-center">
                    <button id="convertRsdToEur" class="btn btn-info">Konvertuj RSD u EUR</button>
                </div>
            </div>
            
            <div class="row mt-3" id="conversionResult" style="display: none;">
                <div class="col-md-4 offset-md-4">
                    <div class="total-card" style="background-color: #f8f9d2;">
                        <h5>Konvertovani RSD u EUR</h5>
                        <div class="total-amount" style="color: #6b5b95;" id="convertedAmount">0.00 €</div>
                        <div class="total-amount" style="font-size: 14px; color: #666;" id="exchangeRate">Kurs: 1 RSD = 0.00 EUR</div>
                        <div class="total-amount" style="font-size: 14px; color: #666;" id="lastUpdated">Poslednje ažuriranje: -</div>
                    </div>
                </div>
            </div>
            
            <div class="row mt-4">
                <div class="col-md-12">
                    <h4>Grafički prikaz poslednjih unosa</h4>
                    <div class="chart-container" style="position: relative; height:400px;">
                        <canvas id="entriesChart"></canvas>
                    </div>
                    <?php if (empty($ljubo_entries) && empty($maja_entries)) { ?>
                        <div class="alert alert-info mt-3 text-center">Nema unosa za prikaz</div>
                    <?php } ?>
                </div>
            </div>
            
            <?php
            // Prepare data for the chart
            $chart_labels = [];
            $ljubo_eur_data = [];
            $ljubo_rsd_data = [];
            $maja_eur_data = [];
            $maja_rsd_data = [];
            
            // Get the last 5 entries for LJUBO
            $count = 0;
            foreach ($ljubo_entries as $entry) {
                if ($count >= 5) break;
                $chart_labels[] = formatDate($entry["date"]);
                $ljubo_eur_data[] = $entry["total"];
                $ljubo_rsd_data[] = $entry["rsd_total"];
                $count++;
            }
            
            // Get the last 5 entries for MAJA
            $count = 0;
            foreach ($maja_entries as $entry) {
                if ($count >= 5) break;
                // Check if this date is already in labels (to avoid duplicates)
                $date = formatDate($entry["date"]);
                if (!in_array($date, $chart_labels)) {
                    $chart_labels[] = $date;
                }
                $maja_eur_data[$count] = $entry["total"];
                $maja_rsd_data[$count] = $entry["rsd_total"];
                $count++;
            }
            
            // Sort the dates chronologically
            array_multisort($chart_labels, SORT_ASC);
            ?>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
        $(document).ready(function() {
            // Create the bar chart for entries
            var ctx = document.getElementById('entriesChart').getContext('2d');
            var entriesChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: <?php echo json_encode($chart_labels); ?>,
                    datasets: [
                        {
                            label: 'LJUBOMIR EUR',
                            data: <?php echo json_encode($ljubo_eur_data); ?>,
                            backgroundColor: 'rgba(54, 162, 235, 0.6)',
                            borderColor: 'rgba(54, 162, 235, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'LJUBOMIR RSD',
                            data: <?php echo json_encode($ljubo_rsd_data); ?>,
                            backgroundColor: 'rgba(75, 192, 192, 0.6)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'MAJA EUR',
                            data: <?php echo json_encode($maja_eur_data); ?>,
                            backgroundColor: 'rgba(255, 99, 132, 0.6)',
                            borderColor: 'rgba(255, 99, 132, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'MAJA RSD',
                            data: <?php echo json_encode($maja_rsd_data); ?>,
                            backgroundColor: 'rgba(255, 159, 64, 0.6)',
                            borderColor: 'rgba(255, 159, 64, 1)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            title: {
                                display: true,
                                text: 'Vrednost'
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Datum'
                            }
                        }
                    },
                    plugins: {
                        title: {
                            display: true,
                            text: 'Uporedni prikaz poslednjih unosa',
                            font: {
                                size: 16
                            }
                        },
                        legend: {
                            position: 'top'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    var label = context.dataset.label || '';
                                    if (label) {
                                        label += ': ';
                                    }
                                    if (context.parsed.y !== null) {
                                        label += new Intl.NumberFormat('sr-RS', { 
                                            style: 'decimal',
                                            minimumFractionDigits: 2,
                                            maximumFractionDigits: 2
                                        }).format(context.parsed.y);
                                    }
                                    return label;
                                }
                            }
                        }
                    }
                }
            });
            
            // Format date inputs to display in DD/MM/YYYY format
            $('input[type="date"]').each(function() {
                // Add a label to show the formatted date
                var dateLabel = $('<span class="date-format-label"></span>');
                $(this).after(dateLabel);
                
                // Update the label when date changes
                $(this).on('change', function() {
                    var date = new Date($(this).val());
                    if(!isNaN(date.getTime())) {
                        var day = date.getDate().toString().padStart(2, '0');
                        var month = (date.getMonth() + 1).toString().padStart(2, '0');
                        var year = date.getFullYear();
                        var formattedDate = day + '/' + month + '/' + year;
                        $(this).next('.date-format-label').text('Format: ' + formattedDate);
                    }
                }).trigger('change');
            });
            
            // Convert RSD to EUR button click handler
            $("#convertRsdToEur").click(function() {
                const grandRsdTotal = <?php echo $grand_rsd_total; ?>;
                const button = $(this);
                
                // Show loading state
                button.prop('disabled', true);
                button.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Konvertujem...');
                
                // Call the exchange rate API to get the latest RSD to EUR rate
                $.ajax({
                    url: 'https://open.er-api.com/v6/latest/RSD',
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        // Get the exchange rate
                        const exchangeRate = data.rates.EUR;
                        const convertedAmount = grandRsdTotal * exchangeRate;
                        
                        // Format date as DD/MM/YYYY HH:MM
                        const updateDate = new Date(data.time_last_update_utc);
                        const day = updateDate.getDate().toString().padStart(2, '0');
                        const month = (updateDate.getMonth() + 1).toString().padStart(2, '0');
                        const year = updateDate.getFullYear();
                        const hours = updateDate.getHours().toString().padStart(2, '0');
                        const minutes = updateDate.getMinutes().toString().padStart(2, '0');
                        const lastUpdated = `${day}/${month}/${year} ${hours}:${minutes}`;
                        
                        // Update the conversion result
                        $("#convertedAmount").text(convertedAmount.toFixed(2) + ' €');
                        $("#exchangeRate").text('Kurs: 1 RSD = ' + exchangeRate.toFixed(6) + ' EUR');
                        $("#lastUpdated").text('Poslednje ažuriranje: ' + lastUpdated);
                        
                        // Show the conversion result
                        $("#conversionResult").fadeIn();
                        
                        // Reset button state
                        button.prop('disabled', false);
                        button.html('Konvertuj RSD u EUR');
                    },
                    error: function(xhr, status, error) {
                        // Handle error
                        alert('Greška pri preuzimanju kursa: ' + error);
                        
                        // Reset button state
                        button.prop('disabled', false);
                        button.html('Konvertuj RSD u EUR');
                    }
                });
            });
        });
    </script>
</body>
</html>
