<?php
// create_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_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['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();
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get form data
    $deposit_date = $_POST['deposit_date'];
    $currency = $_POST['currency'];
    $amount = $_POST['amount'];
    $purpose = $_POST['purpose'];
    $source = $_POST['source'];
    $bank = $_POST['bank'];
    $deposit_user_id = $_POST['deposit_user_id'];
    $approval_user_id = $_POST['approval_user_id'];
    
    // Validate input
    $errors = [];
    
    if (empty($deposit_date)) {
        $errors[] = "Deposit date is required.";
    }
    
    if (empty($currency)) {
        $errors[] = "Currency is required.";
    }
    
    if (empty($amount) || !is_numeric($amount) || $amount <= 0) {
        $errors[] = "Amount must be a positive number.";
    }
    
    if (empty($purpose)) {
        $errors[] = "Purpose is required.";
    }
    
    if (empty($source)) {
        $errors[] = "Deposit source is required.";
    }
    
    if (empty($bank)) {
        $errors[] = "Bank is required.";
    }
    
    if (empty($deposit_user_id)) {
        $errors[] = "Deposit user is required.";
    }
    
    if (empty($approval_user_id)) {
        $errors[] = "Approval user is required.";
    }
    
    // If no errors, insert the record
    if (empty($errors)) {
        try {
            // Begin transaction
            $conn->begin_transaction();
            
            // Insert deposit record
            $sql = "INSERT INTO deposits (
                        deposit_date, currency, amount, purpose, source, bank, 
                        deposit_user_id, approval_user_id, created_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                'ssdsssiis', 
                $deposit_date, $currency, $amount, $purpose, $source, $bank, 
                $deposit_user_id, $approval_user_id, $user_id
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Error creating deposit: " . $stmt->error);
            }
            
            // Get the inserted ID
            $deposit_id = $conn->insert_id;
            
            // Commit the transaction
            $conn->commit();
            
            $_SESSION['success_message'] = "Deposit created successfully.";
            header('Location: deposit_list.php');
            exit();
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            
            $error_message = $e->getMessage();
        }
    }
}

// Get users for dropdowns
$users_query = "SELECT user_id, full_name FROM users WHERE role_id IN (1, 3) ORDER BY full_name";
$users_result = $conn->query($users_query);

$users = [];
if ($users_result->num_rows > 0) {
    while ($row = $users_result->fetch_assoc()) {
        $users[] = $row;
    }
}

// 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' => 'Create Deposit')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Flatpickr CSS -->
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet" type="text/css">
    
    <!-- Select2 CSS -->
    <link href="assets/libs/select2/select2.min.css" rel="stylesheet" type="text/css">
    
    <style>
        .form-label {
            font-weight: 500;
        }
        .required:after {
            content: " *";
            color: red;
        }
        .select2-container--default .select2-selection--single {
            height: 38px;
            border-color: #ced4da;
        }
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
        }
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }
    </style>
</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' => 'Create Deposit')); ?>

                    <?php
                    // Show error message if set
                    if (isset($error_message)) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $error_message;
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                    }
                    
                    // Show validation errors if any
                    if (!empty($errors)) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo '<ul class="mb-0">';
                        foreach ($errors as $error) {
                            echo '<li>' . $error . '</li>';
                        }
                        echo '</ul>';
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                    }
                    ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Deposit Information</h4>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="">
                                        <div class="row g-3">
                                            <div class="col-md-6">
                                                <label for="deposit_date" class="form-label required">Deposit Date</label>
                                                <input type="text" class="form-control flatpickr-input" id="deposit_date" name="deposit_date" placeholder="Select date" required>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="bank" class="form-label required">Bank</label>
                                                <select class="form-select" id="bank" name="bank" required>
                                                    <option value="">Select Bank</option>
                                                    <option value="Ecobank">Ecobank</option>
                                                    <option value="I & M Bank">I & M Bank</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="currency" class="form-label required">Currency</label>
                                                <select class="form-select" id="currency" name="currency" required>
                                                    <option value="">Select Currency</option>
                                                    <option value="USD">USD</option>
                                                    <option value="Tsh">Tsh</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="amount" class="form-label required">Amount</label>
                                                <input type="number" class="form-control" id="amount" name="amount" step="0.01" min="0" placeholder="Enter amount" required>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label for="source" class="form-label required">Deposit Source</label>
                                                <input type="text" class="form-control" id="source" name="source" placeholder="Enter Deposit Source" required>
                                            </div>
                                            
                                            <div class="col-md-12">
                                                <label for="purpose" class="form-label required">Purpose</label>
                                                <textarea class="form-control" id="purpose" name="purpose" rows="3" placeholder="Enter purpose of deposit" required></textarea>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="deposit_user_id" class="form-label required">Deposit User</label>
                                                <select class="form-select" id="deposit_user_id" name="deposit_user_id" required>
                                                    <option value="">Select User</option>
                                                    <?php foreach ($users as $user): ?>
                                                    <option value="<?php echo $user['user_id']; ?>"><?php echo $user['full_name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label for="approval_user_id" class="form-label required">Approval User</label>
                                                <select class="form-select" id="approval_user_id" name="approval_user_id" required>
                                                    <option value="">Select User</option>
                                                    <?php foreach ($users as $user): ?>
                                                    <option value="<?php echo $user['user_id']; ?>"><?php echo $user['full_name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-12 mt-4 text-end">
                                                <a href="deposit_list.php" class="btn btn-secondary me-2">Cancel</a>
                                                <button type="submit" class="btn btn-primary">Create Deposit</button>
                                            </div>
                                        </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'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <!-- Flatpickr js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize flatpickr
            flatpickr("#deposit_date", {
                dateFormat: "Y-m-d",
                defaultDate: "today",
                maxDate: "today"
            });
            
            // Initialize Select2
            $(".select2").select2({
                width: '100%',
                placeholder: "Select an option"
            });
        });
    </script>

</body>
</html>