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

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

// Check if user has permission (admin or operations)
$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'];
}

// Restrict access to admin and 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();
}

// 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";
}

// Get banks list
$sql_banks = "SELECT id, bank_name FROM banks WHERE status = 'active' ORDER BY bank_name";
$result_banks = $conn->query($sql_banks);
$banks = [];
if ($result_banks && $result_banks->num_rows > 0) {
    while ($row = $result_banks->fetch_assoc()) {
        $banks[$row['id']] = $row['bank_name'];
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $withdrawal_date = $_POST['withdrawal_date'];
    $currency = $_POST['currency'];
    $amount = $_POST['amount'];
    $purpose = $_POST['purpose'];
    $bank = $_POST['bank'];
    $bank_branch = $_POST['bank_branch'] ?? null;
    $cheque_number = $_POST['cheque_number'] ?? null;
    
    // Validate input
    $errors = [];
    
    if (empty($withdrawal_date)) {
        $errors[] = "Withdrawal date is required.";
    }
    
    if (empty($currency)) {
        $errors[] = "Currency is required.";
    }
    
    if (!is_numeric($amount) || $amount <= 0) {
        $errors[] = "Amount must be a positive number.";
    }
    
    if (empty($purpose)) {
        $errors[] = "Purpose is required.";
    }
    
    if (empty($bank)) {
        $errors[] = "Bank is required.";
    }
    
    // If no errors, save to database
    if (empty($errors)) {
        try {
            // Get bank name from ID
            $bank_name = '';
            foreach ($banks as $id => $name) {
                if ($id == $bank) {
                    $bank_name = $name;
                    break;
                }
            }
            
            $sql = "INSERT INTO cheque_withdrawals (
                        withdrawal_date, currency, amount, purpose, bank, bank_branch,
                        cheque_number, withdrawal_user_id, status
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending')";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param(
                'ssdssssi',
                $withdrawal_date,
                $currency,
                $amount,
                $purpose,
                $bank_name,
                $bank_branch,
                $cheque_number,
                $user_id
            );
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Cheque withdrawal request created successfully.";
                header('Location: cheque_withdrawals.php');
                exit();
            } else {
                throw new Exception($stmt->error);
            }
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Error creating withdrawal request: " . $e->getMessage();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
    }
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Cheque Withdrawal')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Datepicker css -->
    <link rel="stylesheet" href="assets/libs/flatpickr/flatpickr.min.css">
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .form-section {
            margin-bottom: 30px;
        }
        .form-section-title {
            border-bottom: 1px solid #e9e9ef;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 3px;
        }
    </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 Cheque Withdrawal')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // 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-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Create Cheque Withdrawal Request</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST" id="withdrawal-form">
                                        <div class="form-section">
                                            <h5 class="form-section-title">Withdrawal Details</h5>
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label for="withdrawal_date" class="form-label required-field">Withdrawal Date</label>
                                                    <input type="text" class="form-control flatpickr-input" id="withdrawal_date" name="withdrawal_date" placeholder="YYYY-MM-DD" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="currency" class="form-label required-field">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-6 mb-3">
                                                    <label for="amount" class="form-label required-field">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-6 mb-3">
                                                    <label for="bank" class="form-label required-field">Bank</label>
                                                    <select class="form-select" id="bank" name="bank" required>
                                                        <option value="">Select Bank</option>
                                                        <?php foreach ($banks as $id => $name): ?>
                                                        <option value="<?php echo $id; ?>"><?php echo $name; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="bank_branch" class="form-label">Bank Branch</label>
                                                    <input type="text" class="form-control" id="bank_branch" name="bank_branch" placeholder="Enter bank branch">
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label for="cheque_number" class="form-label">Cheque Number</label>
                                                    <input type="text" class="form-control" id="cheque_number" name="cheque_number" placeholder="Enter cheque number">
                                                </div>
                                                <div class="col-md-12 mb-3">
                                                    <label for="purpose" class="form-label required-field">Purpose</label>
                                                    <textarea class="form-control" id="purpose" name="purpose" rows="4" placeholder="Enter the purpose of withdrawal" required></textarea>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="text-end">
                                            <a href="cheque_withdrawals.php" class="btn btn-secondary me-2">Cancel</a>
                                            <button type="submit" class="btn btn-primary">Submit Request</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'; ?>
    <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>
    <!-- Datepicker js -->
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize flatpickr date picker
            flatpickr("#withdrawal_date", {
                dateFormat: "Y-m-d",
                defaultDate: new Date()
            });
            
            // Form validation
            $('#withdrawal-form').on('submit', function(e) {
                var valid = true;
                
                // Check required fields
                $(this).find('[required]').each(function() {
                    if ($(this).val() === '') {
                        $(this).addClass('is-invalid');
                        valid = false;
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                // Check amount is positive
                var amount = $('#amount').val();
                if (amount <= 0) {
                    $('#amount').addClass('is-invalid');
                    valid = false;
                }
                
                if (!valid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please fill all required fields and ensure amount is positive.',
                        confirmButtonColor: '#3085d6'
                    });
                }
            });
        });
    </script>

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