<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../classes/Branch.php';

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

$auth = new Auth($conn);
$order = new Order($conn);
$branch = new Branch($conn);

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


$orderId = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$orderData = $order->getOrderById($orderId) ?? [];
if (!$orderData || ($auth->getUserBranch($_SESSION['user_id']) != ($orderData['branch_id'] ?? null) && !$auth->isSuperAdmin($_SESSION['user_id']))) {
    header('Location: list_orders.php?error=' . urlencode('Order not found or access denied.'));
    exit();
}


$branchId = $orderData['branch_id'] ?? null;
$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

if ($isSuperAdmin) {
    if (!$branchId) {
        header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Please select a branch.'));
        exit();
    }

    try {
        $branches = $branch->getAllBranches();
        $validBranch = false;
        foreach ($branches->fetchAll(PDO::FETCH_ASSOC) as $b) {
            if ($b['branch_id'] == $branchId) {
                $validBranch = true;
                break;
            }
        }
        if (!$validBranch) {
            header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Invalid branch selected.'));
            exit();
        }
    } catch (PDOException $e) {
        error_log("PDO Error in branch validation: " . $e->getMessage());
        header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Database error: ' . $e->getMessage()));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
} else {
    $branchId = $userBranchId;
    if (!$branchId) {
        header('Location: ../../login.php?error=' . urlencode('No branch assigned to this user.'));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemName = trim($_POST['item_name'] ?? $orderData['item_name'] ?? '');
    $price = (float)($_POST['price'] ?? $orderData['price'] ?? 0);
    $customerName = trim($_POST['customer_name'] ?? $orderData['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? $orderData['customer_contact'] ?? '');
    $amountPaid = (float)($_POST['amount_paid'] ?? $orderData['amount_paid'] ?? 0);
    $deliveryDate = $_POST['delivery_date'] ?? $orderData['delivery_date'] ?? date('Y-m-d', strtotime('+7 days'));
    $status = $_POST['status'] ?? $orderData['status'] ?? 'pending';
    $notes = trim($_POST['notes'] ?? $orderData['notes'] ?? '');

    if (empty($itemName) || $price <= 0 || empty($customerName) || empty($customerContact) || $amountPaid < 0) {
        $error = 'Please fill in all required fields with valid values.';
    } else {
        try {
            $result = $order->updateOrder($orderId, $itemName, $price, $customerName, $customerContact, $amountPaid, $deliveryDate, $status, $notes);
            if ($result) {
                header('Location: list_orders.php?success=' . urlencode('Order updated successfully.') . '&branch_id=' . $branchId);
                exit();
            } else {
                $error = 'Failed to update order.';
            }
        } catch (Exception $e) {
            error_log("Error updating order: " . $e->getMessage());
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .order-header {
            background: linear-gradient(45deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .company-name {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .company-tagline {
            font-size: 14px;
            margin-bottom: 20px;
            opacity: 0.9;
            line-height: 1.6;
        }

        .company-details {
            font-size: 12px;
            line-height: 1.8;
            opacity: 0.8;
        }

        .order-title {
            position: absolute;
            top: 30px;
            right: 30px;
            background: #e74c3c;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            font-size: 18px;
        }

        .order-number {
            position: absolute;
            top: 80px;
            right: 30px;
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
        }

        .form-container {
            padding: 40px;
        }

        .form-section {
            margin-bottom: 30px;
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 4px solid #3498db;
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            width: 30px;
            height: 30px;
            background: linear-gradient(45deg, #3498db, #2980b9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .required {
            color: #e74c3c;
        }

        .form-control {
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            transform: translateY(-1px);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 80px;
        }

        .action-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #e9ecef;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(52, 152, 219, 0.3);
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(39, 174, 96, 0.3);
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

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

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

        @media (max-width: 768px) {
            .container {
                margin: 10px;
                border-radius: 10px;
            }

            .order-header {
                padding: 20px;
            }

            .order-title,
            .order-number {
                position: static;
                margin: 10px 0;
                display: inline-block;
            }

            .form-container {
                padding: 20px;
            }

            .action-buttons {
                flex-direction: column;
                gap: 15px;
            }
        }

        .container {
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
    </style>
    <div class="container">
        <div class="order-header">
            <div class="order-title">EDIT ORDER</div>
            <div class="order-number">No. <?php echo htmlspecialchars($orderData['order_id'] ?? 'N/A'); ?></div>
            <div class="company-name"><?php echo htmlspecialchars($companyName); ?></div>
            <div class="company-tagline">
                Dealers in: IT Consumables & Electricals, Desktop Computers, Laptops,<br>
                Projectors, Computer Accessories, Digital Home Theaters, Stereo Headphones,<br>
                Household Furniture's & many more
            </div>
            <div class="company-details">
                P.O. Box 109, Limbe, Malawi, South East Africa<br>
                Tel: +265 (0) 212 273 707 / Cell: +265 (0) 888 737 654<br>
                Email: blessvantengani@gmail.com / Web: www.brcomputers.mw
            </div>
        </div>

        <div class="form-container">
            <?php if (isset($error)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php elseif (isset($_GET['error'])): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars(urldecode($_GET['error'])); ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="" id="orderForm" class="needs-validation" novalidate>
                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-user"></i>
                        </div>
                        Order Information
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label for="item_name" class="form-label">
                                <i class="fas fa-box"></i>
                                Item Name: <span class="required">*</span>
                            </label>
                            <input type="text" class="form-control" id="item_name" name="item_name"
                                   value="<?php echo htmlspecialchars($orderData['item_name'] ?? ''); ?>" required>
                        </div>

                        <div class="form-group">
                            <label for="price" class="form-label">
                                <i class="fas fa-dollar-sign"></i>
                                Price (MWK): <span class="required">*</span>
                            </label>
                            <input type="number" class="form-control" id="price" name="price"
                                   value="<?php echo htmlspecialchars($orderData['price'] ?? ''); ?>" step="0.01" min="0" required>
                        </div>

                        <div class="form-group full-width">
                            <label for="customer_name" class="form-label">
                                <i class="fas fa-building"></i>
                                Customer/Company Name: <span class="required">*</span>
                            </label>
                            <input type="text" class="form-control" id="customer_name" name="customer_name"
                                   value="<?php echo htmlspecialchars($orderData['customer_name'] ?? ''); ?>" required>
                        </div>

                        <div class="form-group full-width">
                            <label for="customer_contact" class="form-label">
                                <i class="fas fa-address-book"></i>
                                Contact Details: <span class="required">*</span>
                            </label>
                            <textarea class="form-control" id="customer_contact" name="customer_contact"
                                      placeholder="Address, Phone, Email" required><?php echo htmlspecialchars($orderData['customer_contact'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label for="amount_paid" class="form-label">
                                <i class="fas fa-money-bill"></i>
                                Amount Paid (MWK): <span class="required">*</span>
                            </label>
                            <input type="number" class="form-control" id="amount_paid" name="amount_paid"
                                   value="<?php echo htmlspecialchars($orderData['amount_paid'] ?? '0'); ?>" step="0.01" min="0" required>
                        </div>

                        <div class="form-group">
                            <label for="delivery_date" class="form-label">
                                <i class="fas fa-calendar"></i>
                                Delivery Date: <span class="required">*</span>
                            </label>
                            <input type="date" class="form-control" id="delivery_date" name="delivery_date"
                                   value="<?php echo htmlspecialchars($orderData['delivery_date'] ?? date('Y-m-d', strtotime('+7 days'))); ?>" required>
                        </div>

                        <div class="form-group">
                            <label for="status" class="form-label">
                                <i class="fas fa-check-circle"></i>
                                Status: <span class="required">*</span>
                            </label>
                            <select class="form-control" id="status" name="status" required>
                                <option value="pending" <?php echo ($orderData['status'] ?? 'pending') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo ($orderData['status'] ?? 'pending') === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                <option value="rejected" <?php echo ($orderData['status'] ?? 'pending') === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                <option value="delivered" <?php echo ($orderData['status'] ?? 'pending') === 'delivered' ? 'selected' : ''; ?>>Delivered</option>
                                <option value="completed" <?php echo ($orderData['status'] ?? 'pending') === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-sticky-note"></i>
                        </div>
                        Additional Notes
                    </div>

                    <div class="form-group">
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                                  placeholder="Any additional notes or terms..."><?php echo htmlspecialchars($orderData['notes'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="action-buttons">
                    <a href="list_orders.php?branch_id=<?php echo $branchId; ?>" class="btn btn-secondary">
                        <i class="fas fa-times"></i>
                        Cancel
                    </a>

                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i>
                        Update Order
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('orderForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
