<?php
// edit_deposit.php
session_start();
include 'layouts/dbconn.php';

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

// Get user details for permission checks
$user_id = $_SESSION['user_id'];
$sql_user = "SELECT user_role, role_id FROM users WHERE user_id = $user_id";
$result_user = $conn->query($sql_user);
$row_user = $result_user->fetch_assoc();
$role_id = $row_user['role_id'];

// Check if user has access (admin or operations roles)
if ($role_id != 1 && $role_id != 3) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No deposit ID provided";
    header('Location: deposit_list.php');
    exit();
}

$deposit_id = intval($_GET['id']);

// Fetch deposit details
$sql = "SELECT * FROM deposits WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $deposit_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Deposit not found";
    header('Location: deposit_list.php');
    exit();
}

$deposit = $result->fetch_assoc();

// Check if deposit is in pending status
if ($deposit['status'] !== 'pending') {
    $_SESSION['error_message'] = "Only pending deposits can be edited";
    header('Location: deposit_list.php');
    exit();
}

// Get banks for dropdown
$sql_banks = "SELECT id, bank_name FROM banks WHERE status = 'active'";
$result_banks = $conn->query($sql_banks);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate and sanitize input
    $deposit_date = $_POST['deposit_date'];
    $bank = $_POST['bank'];
    $currency = $_POST['currency'];
    $amount = floatval($_POST['amount']);
    $purpose = $_POST['purpose'];
    $source = $_POST['source'];
    
    // Check for required fields
    if (empty($deposit_date) || empty($bank) || empty($amount) || empty($purpose) || empty($source)) {
        $_SESSION['error_message'] = "All fields are required";
    } else {
        // Update deposit in database
        $sql_update = "UPDATE deposits SET 
                        deposit_date = ?, 
                        bank = ?, 
                        currency = ?, 
                        amount = ?, 
                        purpose = ?, 
                        source = ? 
                      WHERE id = ?";
        
        $stmt_update = $conn->prepare($sql_update);
        $stmt_update->bind_param("sssdssi", $deposit_date, $bank, $currency, $amount, $purpose, $source, $deposit_id);
        
        if ($stmt_update->execute()) {
            $_SESSION['success_message'] = "Deposit updated successfully";
            header('Location: deposit_list.php');
            exit();
        } else {
            $_SESSION['error_message'] = "Error updating deposit: " . $conn->error;
        }
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Deposit')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Datepicker CSS -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.css">
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance Management', 'title' => 'Edit Deposit')); ?>

                    <?php
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-xxl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Edit Deposit</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="deposit_date" class="form-label">Deposit Date <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" id="deposit_date" name="deposit_date" value="<?php echo $deposit['deposit_date']; ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="bank" class="form-label">Bank <span class="text-danger">*</span></label>
                                                <select class="form-select" id="bank" name="bank" required>
                                                    <option value="">Select Bank</option>
                                                    <?php
                                                    if ($result_banks && $result_banks->num_rows > 0) {
                                                        while ($bank = $result_banks->fetch_assoc()) {
                                                            $selected = ($bank['bank_name'] == $deposit['bank']) ? 'selected' : '';
                                                            echo "<option value='" . $bank['bank_name'] . "' " . $selected . ">" . $bank['bank_name'] . "</option>";
                                                        }
                                                    } else {
                                                        // If no banks found, add the current bank as an option
                                                        echo "<option value='" . $deposit['bank'] . "' selected>" . $deposit['bank'] . "</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="currency" class="form-label">Currency <span class="text-danger">*</span></label>
                                                <select class="form-select" id="currency" name="currency" required>
                                                    <option value="USD" <?php echo ($deposit['currency'] == 'USD') ? 'selected' : ''; ?>>USD</option>
                                                    <option value="TSH" <?php echo ($deposit['currency'] == 'TSH') ? 'selected' : ''; ?>>TSH</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="amount" class="form-label">Amount <span class="text-danger">*</span></label>
                                                <input type="number" step="0.01" class="form-control" id="amount" name="amount" value="<?php echo $deposit['amount']; ?>" required>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="source" class="form-label">Source <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="source" name="source" value="<?php echo $deposit['source']; ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="purpose" class="form-label">Purpose <span class="text-danger">*</span></label>
                                                <textarea class="form-control" id="purpose" name="purpose" rows="3" required><?php echo $deposit['purpose']; ?></textarea>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <a href="deposit_list.php" class="btn btn-light me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary">Update Deposit</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Datepicker js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize flatpickr
            flatpickr("#deposit_date", {
                dateFormat: "Y-m-d",
                allowInput: true
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>