<?php
session_start();
include('includes/head.php');

// Check PIN
$admin_pin = "1234";
$submitted_pin = isset($_POST['admin_pin']) ? trim($_POST['admin_pin']) : '';

if ($submitted_pin !== $admin_pin) {
    header('Location: monthly_report.php?error=Invalid PIN. Notes not saved.');
    exit();
}

// Get form data
$month = intval($_POST['month']);
$year = intval($_POST['year']);
$performance = mysqli_real_escape_string($conn, $_POST['performance']);
$achievement = mysqli_real_escape_string($conn, $_POST['achievement']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$admin_id = $_SESSION['admin_id'] ?: 1;
$admin_name = $_SESSION['admin_name'] ?: 'System Admin';

// Create table if not exists
$create_table = "CREATE TABLE IF NOT EXISTS monthly_reports (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    report_month INT(2) NOT NULL,
    report_year INT(4) NOT NULL,
    performance VARCHAR(20),
    achievement TEXT,
    notes TEXT,
    admin_id INT(11),
    admin_name VARCHAR(255),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY month_year (report_month, report_year)
)";
mysqli_query($conn, $create_table);

// Insert or update
$check_sql = "SELECT id FROM monthly_reports WHERE report_month = $month AND report_year = $year";
$check_result = mysqli_query($conn, $check_sql);

if (mysqli_num_rows($check_result) > 0) {
    $sql = "UPDATE monthly_reports SET 
            performance = '$performance',
            achievement = '$achievement',
            notes = '$notes',
            admin_id = $admin_id,
            admin_name = '$admin_name'
            WHERE report_month = $month AND report_year = $year";
} else {
    $sql = "INSERT INTO monthly_reports (report_month, report_year, performance, achievement, notes, admin_id, admin_name) 
            VALUES ($month, $year, '$performance', '$achievement', '$notes', $admin_id, '$admin_name')";
}

if (mysqli_query($conn, $sql)) {
    logAdminActivity(
        'Monthly Report Saved',
        "Saved monthly report notes for " . date('F Y', strtotime("$year-$month-01")),
        'Reports',
        $month,
        'monthly_reports'
    );
    
    header('Location: monthly_report.php?month=' . $month . '&year=' . $year . '&success=Monthly notes saved successfully!');
} else {
    header('Location: monthly_report.php?month=' . $month . '&year=' . $year . '&error=Failed to save notes.');
}
exit();
?>