<?php

require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../includes/dashboard_helper.php';


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


$database = new Database();
$conn = $database->getConnection();


$auth = new Auth($conn);


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id']) &&
    !$auth->isSalesAssistant($_SESSION['user_id'])) {
    header('Location: ../../unauthorized.php');
    exit;
}


if ($auth->isSuperAdmin($_SESSION['user_id'])) {
    $userRole = 'admin';
} elseif ($auth->isWarehousePersonnel($_SESSION['user_id'])) {
    $userRole = 'warehouse';
} elseif ($auth->isBranchManager($_SESSION['user_id']) || $auth->isSalesAssistant($_SESSION['user_id'])) {
    $userRole = 'branch_manager';
} else {
    $userRole = 'admin';
}


if (!function_exists('getDashboardLink')) {
    function getDashboardLink() {
        if (isset($_SESSION['role'])) {
            switch ($_SESSION['role']) {
                case 'super_admin':
                    return '../dashboard/admin.php';
                case 'branch_manager':
                case 'sales_assistant':
                case 'warehouse_personnel':
                    return '../dashboard/branch.php';
                default:
                    return '../dashboard/branch.php';
            }
        }
        return '../dashboard/branch.php';
    }
}


$inventory = new Inventory($conn);

$message = null;
$messageType = 'success';
$previewItems = [];
$newPercentage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $newPercentage = trim($_POST['new_percentage'] ?? '');
    $action = $_POST['action'] ?? 'preview';

    if ($newPercentage === '' || !is_numeric($newPercentage)) {
        $message = 'Enter a valid percentage.';
        $messageType = 'danger';
    } elseif ((float)$newPercentage < -100) {
        $message = 'Percentage cannot be less than -100%.';
        $messageType = 'danger';
    } else {
        $actualValue = ((float)$newPercentage) / 100;

        try {
            if ($action === 'confirm') {
                $updatedCount = $inventory->applyPriceChange($actualValue);
                $message = 'Prices changed successfully. ' . number_format($updatedCount) . ' item price(s) updated.';
                $messageType = 'success';
                $newPercentage = '';
            } else {
                $previewItems = $inventory->previewPriceChange($actualValue);
                $message = 'Preview generated. Review the new prices below, then confirm to apply changes.';
                $messageType = 'info';
            }
        } catch (Exception $e) {
            $message = 'Unable to change prices: ' . $e->getMessage();
            $messageType = 'danger';
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<div class="container mt-5">
        <a href="<?php echo getDashboardLink(); ?>" class="btn btn-secondary mb-3">Back to Dashboard</a>

<style>

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Roboto', sans-serif;
        font-size: 14px;
        line-height: 1.6;
        color: #333;
        background-color: #f8f9fa;
    }

    .container {
        width: 100%;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 15px;
    }


    .dashboard-container {
        display: flex;
        width: 100%;
        margin-top: 20px;
    }


    .sidebar {
        width: 250px;
        background-color: #343a40;
        color: white;
        padding: 20px;
        position: fixed;
        top: 0;
        left: 0;
        height: 100vh;
        overflow-y: auto;
        z-index: 100;
    }

    .sidebar-heading {
        padding: 10px 0;
        font-size: 18px;
        font-weight: 500;
        border-bottom: 1px solid rgba(255,255,255,0.1);
        margin-bottom: 15px;
    }

    .sidebar-menu {
        list-style: none;
        padding: 0;
        margin: 0 0 25px 0;
    }

    .sidebar-menu li {
        margin-bottom: 5px;
    }

    .sidebar-menu a {
        display: block;
        padding: 10px 15px;
        color: rgba(255,255,255,0.8);
        text-decoration: none;
        transition: all 0.3s;
        border-radius: 4px;
    }

    .sidebar-menu a:hover, .sidebar-menu a.active {
        background-color: rgba(255,255,255,0.1);
        color: white;
    }

    .sidebar-menu i {
        margin-right: 10px;
        width: 20px;
        text-align: center;
    }

    .sidebar-section {
        margin-bottom: 25px;
    }


    .main-content {
        flex: 1;
        margin-left: 250px;
        padding: 20px;
        width: calc(100% - 250px);
    }


    .card {
        background-color: white;
        border-radius: 5px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        margin-bottom: 20px;
        width: 100%;
    }

    .card-header {
        padding: 15px 20px;
        border-bottom: 1px solid #eee;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .card-header h2, .card-header h5 {
        margin: 0;
        font-size: 1.2rem;
    }

    .card-body {
        padding: 20px;
    }


    .timeline {
        position: relative;
        padding: 20px 0;
    }

    .timeline::before {
        content: '';
        position: absolute;
        left: 30px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #dee2e6;
    }

    .timeline-item {
        position: relative;
        margin-left: 60px;
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 5px;
        border-left: 4px solid #007bff;
    }

    .timeline-item::before {
        content: '';
        position: absolute;
        left: -38px;
        top: 20px;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background: #007bff;
        border: 2px solid #fff;
    }

    .timeline-item.added {
        border-left-color: #28a745;
    }

    .timeline-item.added::before {
        background: #28a745;
    }

    .timeline-item.shipped {
        border-left-color: #ffc107;
    }

    .timeline-item.shipped::before {
        background: #ffc107;
    }

    .timeline-item.received {
        border-left-color: #17a2b8;
    }

    .timeline-item.received::before {
        background: #17a2b8;
    }

    .timeline-item.sold {
        border-left-color: #dc3545;
    }

    .timeline-item.sold::before {
        background: #dc3545;
    }

    .timeline-date {
        font-size: 0.9rem;
        color: #6c757d;
        margin-bottom: 5px;
    }

    .timeline-title {
        font-weight: bold;
        margin-bottom: 5px;
    }

    .timeline-details {
        font-size: 0.9rem;
        color: #495057;
    }


    .alert {
        padding: 15px;
        margin-bottom: 20px;
        border: 1px solid transparent;
        border-radius: 4px;
    }

    .alert-success {
        color: #155724;
        background-color: #d4edda;
        border-color: #c3e6cb;
    }

    .alert-danger {
        color: #721c24;
        background-color: #f8d7da;
        border-color: #f5c6cb;
    }


    .form-group {
        margin-bottom: 15px;
    }

    .form-label {
        display: block;
        margin-bottom: 5px;
        font-weight: 500;
    }

    .form-control {
        width: 100%;
        padding: 8px 12px;
        border: 1px solid #ced4da;
        border-radius: 4px;
        font-size: 14px;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        text-decoration: none;
        display: inline-block;
    }

    .btn-primary {
        background-color: #007bff;
        color: white;
    }

    .btn-primary:hover {
        background-color: #0056b3;
    }


    footer {
        margin-left: 250px;
        background-color: #f8f9fa;
        text-align: center;
        padding: 15px 0;
        border-top: 1px solid #eee;
        width: calc(100% - 250px);
    }


    @media (max-width: 768px) {
        .sidebar {
            width: 200px;
        }
        .main-content, footer {
            margin-left: 200px;
            width: calc(100% - 200px);
        }
    }
</style>

        <div class="container">
            <h1 class="mb-4"> Adjust Prices </h1>
            <?php if ($userRole === 'branch_manager'): ?>
                <p class="text-muted"> Adjust prices of all items in all branches </p>
            <?php elseif ($userRole === 'warehouse'): ?>
                <p class="text-muted">Adjust prices of all items in all branches </p>
            <?php else: ?>
                <p class="text-muted">Adjust prices of all items in all branches </p>
            <?php endif; ?>

            <div class="card">
                <div class="card-header">
                    <h5> Adjust prices in %</h5>
                </div>
                <div class="card-body">
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo htmlspecialchars($messageType); ?>" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                        <div class="form-group">
                            <label for="new_percentage" class="form-label">Enter percentage:</label>
                            <input type="number"
                                   step="0.01"
                                   min="-100"
                                   class="form-control"
                                   id="new_percentage"
                                   name="new_percentage"
                                   value="<?php echo htmlspecialchars($newPercentage); ?>"
                                   placeholder="Example: 10 increases prices by 10, -5 reduces by 5"
                                   required>
                        </div>
                        <button type="submit" name="action" value="preview" class="btn btn-primary">
                            <i class="fas fa-eye"></i> Preview Prices
                        </button>
                    </form>
                </div>
            </div>

            <?php if (!empty($previewItems)): ?>
                <?php
                    $oldTotal = array_sum(array_column($previewItems, 'old_price'));
                    $newTotal = array_sum(array_column($previewItems, 'new_price'));
                    $differenceTotal = $newTotal - $oldTotal;
                ?>
                <div class="card">
                    <div class="card-header">
                        <h5>Price Change Preview</h5>
                    </div>
                    <div class="card-body">
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <div class="alert alert-secondary mb-0">
                                    <strong>Items:</strong> <?php echo number_format(count($previewItems)); ?>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="alert alert-secondary mb-0">
                                    <strong>Current Total:</strong> MWK <?php echo number_format($oldTotal, 2); ?>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="alert alert-secondary mb-0">
                                    <strong>New Total:</strong> MWK <?php echo number_format($newTotal, 2); ?>
                                </div>
                            </div>
                        </div>

                        <div class="table-responsive" style="max-height: 520px; overflow: auto;">
                            <table class="table table-striped table-bordered table-sm">
                                <thead class="table-dark">
                                    <tr>
                                        <th>Item</th>
                                        <th>Item Details</th>
                                        <th>Unique Code</th>
                                        <th class="text-end">Old Price</th>
                                        <th class="text-end">New Price</th>
                                        <th class="text-end">Difference</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($previewItems as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                                            <td><?php echo htmlspecialchars($item['item_details'] ?? 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                                            <td class="text-end">MWK <?php echo number_format($item['old_price'], 2); ?></td>
                                            <td class="text-end">MWK <?php echo number_format($item['new_price'], 2); ?></td>
                                            <td class="text-end <?php echo $item['difference'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                MWK <?php echo number_format($item['difference'], 2); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3">Totals</th>
                                        <th class="text-end">MWK <?php echo number_format($oldTotal, 2); ?></th>
                                        <th class="text-end">MWK <?php echo number_format($newTotal, 2); ?></th>
                                        <th class="text-end <?php echo $differenceTotal >= 0 ? 'text-success' : 'text-danger'; ?>">
                                            MWK <?php echo number_format($differenceTotal, 2); ?>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <form method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="mt-3" onsubmit="return confirm('Apply this price change to all previewed items?');">
                            <input type="hidden" name="new_percentage" value="<?php echo htmlspecialchars($newPercentage); ?>">
                            <button type="submit" name="action" value="confirm" class="btn btn-success">
                                <i class="fas fa-check"></i> Confirm Price Changes
                            </button>
                            <a href="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" class="btn btn-outline-secondary">
                                Cancel
                            </a>
                        </form>
                    </div>
                </div>
            <?php endif; ?>


        </div>
    </div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
