<?php
// START: Staff Payroll Declaration
if (isset($_POST['staff_payroll_btn'])) {
    $staff_name = htmlspecialchars(inject_checker($connection, ucwords($_POST['staff_name'])));
    $staff_salary = isset($_POST['staff_salary']) ? floatval($_POST['staff_salary']) : 0;
    $staff_surcharge = isset($_POST['staff_surcharge']) ? floatval($_POST['staff_surcharge']) : 0;
    $staff_bonus = isset($_POST['staff_bonus']) ? floatval($_POST['staff_bonus']) : 0;
    $staff_allowance = isset($_POST['staff_allowance']) ? floatval($_POST['staff_allowance']) : 0;
    $staff_tax = isset($_POST['staff_tax']) ? floatval($_POST['staff_tax']) : 0;
    $staff_pension = isset($_POST['staff_pension']) ? floatval($_POST['staff_pension']) : 0;
    $date = date('Y-m-d');

    if (empty($staff_name) || $staff_salary <= 0) {
        $_SESSION['msg'] = "No field should be empty or invalid.";
        $_SESSION['type'] = "danger";
    } else {
        $check = $connection->prepare("SELECT id FROM staff_payroll WHERE staff_name = ? AND date = ?");
        $check->bind_param("ss", $staff_name, $date);
        $check->execute();
        $check->store_result();

        if ($check->num_rows > 0) {
            $_SESSION['msg'] = "Payroll for this staff already exists today.";
            $_SESSION['type'] = "warning";
        } else {
            $tax_amount = ($staff_salary * $staff_tax) / 100;
            $pension_amount = ($staff_salary * $staff_pension) / 100;
            $net_salary = ($staff_salary + $staff_bonus + $staff_allowance) - ($staff_surcharge + $tax_amount + $pension_amount);

            $query = "INSERT INTO staff_payroll (staff_name, salary, surcharge, bonus, allowance, tax, pension, net_salary, date) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $connection->prepare($query);
            $stmt->bind_param("sddddddds", $staff_name, $staff_salary, $staff_surcharge, $staff_bonus, $staff_allowance, $staff_tax, $staff_pension, $net_salary, $date);

            if ($stmt->execute()) {
                $_SESSION['msg'] = "Staff payroll saved successfully.";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Failed to save staff payroll.";
                $_SESSION['type'] = "danger";
            }
            $stmt->close();
        }
        $check->close();
    }

    // Redirect to staff payroll page after submission
    header("Location: staff_payroll");
    exit;
}

// START: Staff Payroll Deletion
if (isset($_POST['payroll_delete_btn'])) {
    $payroll_hidden_id = intval($_POST['payroll_hidden_id']);

    $stmt = $connection->prepare("DELETE FROM staff_payroll WHERE id = ?");
    $stmt->bind_param("i", $payroll_hidden_id);

    if ($stmt->execute()) {
        $_SESSION['msg'] = "Payroll record deleted successfully.";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Failed to delete payroll record.";
        $_SESSION['type'] = "danger";
    }
    $stmt->close();

    // Redirect after deletion
    header("Location: staff_payroll");
    exit;
}
?>



<div class='page-title'>
  <div>
    <h1><i class='fa fa-laptop'></i> Staff Payroll</h1>
    <p>Record Staff Payments</p>
  </div>  
</div>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>Add Staff to Payroll</h4>
        </div>
        <div class='panel-body'>
            <div class="alert alert-info" role="alert">
              <h5><i class="fas fa-info-circle"></i> How Payroll is Calculated</h5>
              <ul>
                <li><strong>Basic Salary:</strong> The fixed monthly pay for the staff.</li>
                <li><strong>Bonus:</strong> Additional reward or performance-based amount added to the salary.</li>
                <li><strong>Allowance:</strong> Extra benefits such as transport, housing, or feeding allowance.</li>
                <li><strong>Surcharge:</strong> Deductions for lateness, damages, or other penalties.</li>
                <li><strong>Tax:</strong> A percentage of the basic salary is deducted as tax.<br>
                  <code>Tax Amount = (Basic Salary × Tax %) ÷ 100</code>
                </li>
                <li><strong>Pension:</strong> A percentage of the basic salary deducted for pension savings.<br>
                  <code>Pension Amount = (Basic Salary × Pension %) ÷ 100</code>
                </li>
              </ul>
              <p><strong>Net Salary:</strong> This is the final amount paid to staff, calculated as:</p>
              <div class="text-center">
                <code>(Basic Salary + Bonus + Allowance) − (Surcharge + Tax + Pension)</code>
              </div>
            </div>
            <form method='POST' action=''>
                <div class='row'>
                    <div class='col-md-6'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Staff Name</span>
                            <select name='staff_name' class='form-control' required>
                            <option value=''>-- Select Staff --</option>
                            <?php
                            $staff_query = $connection->query("SELECT name FROM staff ORDER BY name ASC");
                            if ($staff_query && $staff_query->num_rows > 0) {
                                while ($row = $staff_query->fetch_assoc()) {
                                    $name = htmlspecialchars($row['name']);
                                    echo "<option value=\"$name\">$name</option>";
                                }
                            } else {
                                echo "<option value=''>No staff found</option>";
                            }
                            ?>
                        </select>
                        </div>
                    </div>
                    <div class='col-md-6'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Basic Salary (₦)</span>
                            <input type='text' name='staff_salary' placeholder='Enter Staff Salary' class='form-control' />
                        </div>
                    </div>                     
                </div>         
                <br />          
                <div class='row'>
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Bonus (₦)</span>
                            <input type='text' name='staff_bonus' placeholder='Enter Bonus' class='form-control' />
                        </div>
                    </div>
					<div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Surcharge (₦)</span>
                            <input type='text' name='staff_surcharge' placeholder='Enter Surcharge' class='form-control' />
                        </div>
                    </div>
                    <div class='col-md-4'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Allowance (₦)</span>
                            <input type='text' name='staff_allowance' placeholder='Enter Allowance' class='form-control' />
                        </div>
                    </div>
               </div>
               <br />
               <div class='row'>
                   <div class='col-md-5'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Tax (%)</span>
                            <input type='text' name='staff_tax' placeholder='Enter Tax' class='form-control' />
                        </div>
                    </div>
                    <div class='col-md-5'>
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>Pension (%)</span>
                            <input type='text' name='staff_pension' placeholder='Enter Pension' class='form-control' />
                        </div>
                    </div>                 
                  <div class='col-md-2'>
                        <p id='btnsubmit'><input type='submit' name='staff_payroll_btn' id='submit' value='Save' class='btn btn-large btn-primary text-center' /></p>
                    </div>
                </div>
            </form>
                

            <?php
                $query = " SELECT sum(net_salary) FROM `staff_payroll` ";
                $run_query = mysqli_query($connection, $query);

                if(mysqli_num_rows($run_query) > 0){
                    while($result = mysqli_fetch_assoc($run_query)){
                        $total_salary = array_sum($result);
                        $total_salary_per_month = number_format($total_salary);
                    }
                }

                $query = " SELECT * FROM `staff_payroll` ";
                $run_query = mysqli_query($connection, $query);

                if(mysqli_num_rows($run_query) > 0){
                    $i = 0;
                    echo"
                        <div class='table-responsive'>
                            <h4 class='text-center'>View Staff Payroll</h4>
                            <table class='table'>
                                <thead class=''>
                                    <tr class='bg-primary'>
                                        <th class='text-center'>S/N</th>
                                        <th class='text-center'>STAFF NAME</th>
                                        <th class='text-center'>BASIC SALARY</th>
                                        <th class='text-center'>ALLOWANCE</th>
                                        <th class='text-center'>BONUS</th>
                                        <th class='text-center'>SURCHARGE</th>
                                        <th class='text-center'>TAX (%)</th>
                                        <th class='text-center'>PENSION (%)</th>
                                        <th class='text-center'>NET SALARY</th>
                                        <th class='text-center'>DATE</th>
                                        <th class='text-center'>ACTION</th>
                                    </tr>
                                </thead>
                    ";
                    while($result = mysqli_fetch_assoc($run_query)){
                        $i++;
                        $staff_id = $result['id'];
                        $staff_name = $result['staff_name'];
                        $staff_salary = number_format($result['salary']);
                        $staff_allowance = number_format($result['allowance']);
                        $staff_bonus = number_format($result['bonus']);
                        $staff_surcharge = number_format($result['surcharge']);
                        $staff_tax = number_format($result['tax']);
                        $staff_pension = number_format($result['pension']);
                        $net_salary = number_format($result['net_salary']);
                        $date = $result['date'];
                        $month = substr($date, 3, 3);
                        $year = substr($date, 7, 4);

                        echo"
                            <tbody>
                                <tr>
                                    <td class='text-center'>{$i}</td>
                                    <td class='text-center'>{$staff_name}</td>
                                    <td class='text-center'>₦{$staff_salary}</td>
                                    <td class='text-center'>₦{$staff_allowance}</td>
                                    <td class='text-center'>₦{$staff_bonus}</td>
                                    <td class='text-center'>₦{$staff_surcharge}</td>
                                    <td class='text-center'>{$staff_tax} %</td>
                                    <td class='text-center'>{$staff_pension} %</td>
                                    <td class='text-center'>₦{$net_salary}</td>
                                    <td class='text-center'>{$date}</td>
                                    <td class='text-center'>
                                        <form method='POST' action=''>
                                            <input type='hidden' name='payroll_hidden_id' value='{$staff_id}' />
                                            <input type='submit' name='payroll_delete_btn' value='Delete' class='btn btn-xs btn-danger' />
                                        </form>
                                    </td>
                                </tr>
                            </tbody>
                        ";
                    }
                    echo"		<tfooter>
                                    <tr>
                                        <th colspan='8' class='text-center'>Total Staff Salaries Per Month</th>
                                        <th colspan='2' class='text-center'>₦{$total_salary_per_month}</th>                                       
                                    </tr>
                                </tfooter>
                            </table>
                        </div>
                    ";
                }else{
                    echo "<h4 class='text-danger'><b>No Records</b></h4>";
                }
            ?>
            <a href="export_payroll_to_excel.php" class="btn btn-success" target="_blank" onclick="setTimeout(() => window.location.href='staff_payroll', 2000)">Export to Excel</a>

        </div>
    </div>
</div>
