<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$zroot  = $_SESSION["zdbroot"];          // sim_root
$zroot1 = substr($zroot, 0, -4);        // sim_   (strips "root")

$user     = $_SESSION["username_" . $dbname];
$password = $_SESSION["password_" . $dbname];
$comp     = $_SESSION["comp_"     . $dbname];
$usertype = $_SESSION["usertype_" . $dbname];
$spltype  = $_SESSION["spltype_"  . $dbname];

$getusercode = mysqli_query($conn,
    "SELECT `code` FROM `passmain`
     WHERE `user`='" . mysqli_real_escape_string($conn, $user) . "'
       AND `password`='" . mysqli_real_escape_string($conn, $password) . "'"
) or die(mysqli_error($conn));
$gusercode = mysqli_fetch_array($getusercode);
$usercode  = $gusercode['code'];

// Fetch company name for display
$getcomp = mysqli_query($conn, "SELECT `name` FROM `company` WHERE `code`='$comp'") or die(mysqli_error($conn));
$fetcomp = mysqli_fetch_array($getcomp);
$cmpname = $fetcomp['name'];

if (isset($_POST["submit"])) {
    $syear = mysqli_real_escape_string($conn, $_POST["cmbyear"]);

    // Year DB name format: sim_2627 (prefix + year, no company code)
    $_SESSION["zdbyear_" . $dbname] = $zroot1 . $syear;
    $_SESSION["tit_"     . $dbname] = $syear;

    $year1 = mysqli_query($conn,
        "SELECT DATE_FORMAT(`startdate`,'%d-%m-%Y') as mfrdt,
                DATE_FORMAT(`lastdate`,'%d-%m-%Y')  as mtodt
         FROM `compyear`
         WHERE `finyear`='$syear'"
    ) or die(mysqli_error($conn));
    $cyear = mysqli_fetch_array($year1);
    $_SESSION["zsdate_" . $dbname] = $cyear['mfrdt'];
    $_SESSION["zedate_" . $dbname] = $cyear['mtodt'];

    header("Location: mainmenu.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $project_title; ?> &mdash; Select Year</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body class="min-h-screen bg-gradient-to-br from-slate-900 via-blue-950 to-slate-800 flex items-center justify-center p-4">

    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">

        <div class="h-1.5 bg-gradient-to-r from-blue-500 via-cyan-400 to-blue-700"></div>

        <div class="p-10">
            <!-- Header -->
            <div class="text-center mb-8">
                <div class="inline-flex items-center justify-center w-14 h-14 bg-blue-700 rounded-full mb-4 shadow-lg">
                    <i class="fa-solid fa-calendar-days text-white text-xl"></i>
                </div>
                <h1 class="text-xl font-bold text-slate-800">Select Financial Year</h1>
                <p class="text-slate-500 text-sm mt-1">
                    Company: <strong class="text-blue-700"><?php echo htmlspecialchars($cmpname); ?></strong>
                </p>
            </div>

            <!-- Form -->
            <form method="POST" action="">

                <div class="mb-3">
                    <label class="block text-xs font-semibold text-gray-600 mb-1.5 uppercase tracking-wide">
                        Financial Year
                    </label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 pl-3 flex items-center text-gray-400 pointer-events-none">
                            <i class="fa fa-calendar text-sm"></i>
                        </span>
                        <select
                            id="cmbyear"
                            name="cmbyear"
                            autofocus
                            class="w-full pl-9 pr-4 py-2.5 border border-gray-300 rounded-lg text-sm
                                   focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent
                                   text-gray-800 bg-white appearance-none transition"
                        >
                            <?php
                            if (true) {
                                $year = mysqli_query($conn,
                                    "SELECT * FROM `compyear`
                                     WHERE `cono`='$comp'
                                     ORDER BY `lastdate` DESC"
                                ) or die(mysqli_error($conn));
                                while ($row = mysqli_fetch_array($year)) {
                                    echo "<option value=\"" . $row['finyear'] . "\">" . htmlspecialchars($row['yearname']) . "</option>";
                                }
                            } else {
                                $year = mysqli_query($conn,
                                    "SELECT `finyear`, `yearname`
                                     FROM `usercomp`
                                     WHERE `cono`='$comp' AND `username`='$usercode'
                                     GROUP BY finyear
                                     ORDER BY `lastdate` DESC"
                                ) or die(mysqli_error($conn));
                                while ($row = mysqli_fetch_array($year)) {
                                    echo "<option value=\"" . $row['finyear'] . "\">" . htmlspecialchars($row['yearname']) . "</option>";
                                }
                            }
                            ?>
                        </select>
                        <span class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 pointer-events-none">
                            <i class="fa fa-chevron-down text-xs"></i>
                        </span>
                    </div>
                </div>

                <!-- AJAX year date display -->
                <div id="yearinfo" class="mb-5 text-center bg-blue-50 border border-blue-100 rounded-lg py-2 min-h-[36px] flex items-center justify-center">
                    <span class="text-blue-400 text-xs">Loading...</span>
                </div>

                <button
                    type="submit"
                    name="submit"
                    class="w-full bg-blue-700 hover:bg-blue-800 active:bg-blue-900
                           text-white font-semibold py-2.5 rounded-lg
                           transition-colors duration-200 text-sm tracking-widest"
                >
                    <i class="fa fa-arrow-right mr-2"></i> OPEN
                </button>

            </form>

            <div class="mt-5 flex justify-center gap-6">
                <a href="comp.php" class="text-xs text-gray-400 hover:text-blue-600 transition-colors">
                    <i class="fa fa-arrow-left mr-1"></i> Back to Company
                </a>
                <a href="logout.php" class="text-xs text-gray-400 hover:text-red-500 transition-colors">
                    <i class="fa fa-power-off mr-1"></i> Logout
                </a>
            </div>
        </div>

        <div class="bg-gray-50 border-t border-gray-100 px-10 py-3 text-center">
            <p class="text-gray-400 text-xs">&copy; <?php echo date('Y'). " " . $project_title; ?></p>
        </div>
    </div>

    <script>
        function loadYearDates() {
            var year = $('#cmbyear').val();
            if (!year) return;
            $.ajax({
                type : 'GET',
                url  : 'ajaxyear.php',
                data : { qyear: year },
                success: function (result) {
                    $('#yearinfo').html(result);
                }
            });
        }

        $(document).ready(function () {
            loadYearDates();
            $('#cmbyear').on('change', function () {
                loadYearDates();
            });
        });
    </script>

</body>
</html>
