<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

require_once '../config/database.php';

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

try {
    $pdo = getDBConnection();
    
    // Get requested date from query parameter, default to today
    $requestedDate = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    
    // Validate date format
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $requestedDate)) {
        $requestedDate = date('Y-m-d');
    }
    
    // Get panchang data for requested date
    $stmt = $pdo->prepare("
        SELECT * FROM panchang_data 
        WHERE date = ? 
        LIMIT 1
    ");
    $stmt->execute([$requestedDate]);
    $requestedData = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // If no data for requested date, generate dynamic data
    if (!$requestedData) {
        $requestedData = generateDynamicPanchang($requestedDate);
    }
    
    // Get panchang data for next 7 days from requested date
    $stmt = $pdo->prepare("
        SELECT * FROM panchang_data 
        WHERE date >= ? 
        ORDER BY date ASC 
        LIMIT 7
    ");
    $stmt->execute([$requestedDate]);
    $weekData = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // If no week data, generate dynamic data for next 7 days
    if (empty($weekData)) {
        $weekData = [];
        for ($i = 0; $i < 7; $i++) {
            $date = date('Y-m-d', strtotime($requestedDate . " +$i days"));
            $weekData[] = generateDynamicPanchang($date);
        }
    }
    
    echo json_encode([
        'success' => true,
        'today_panchang' => $requestedData,
        'week_panchang' => $weekData,
        'total_entries' => count($weekData),
        'requested_date' => $requestedDate
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error fetching panchang data: ' . $e->getMessage()
    ]);
}

// Function to generate dynamic panchang data
function generateDynamicPanchang($date) {
    $dayOfYear = date('z', strtotime($date));
    $dayOfWeek = date('w', strtotime($date));
    
    // Dynamic tithi based on date
    $tithis = ['Pratipada', 'Dwitiya', 'Tritiya', 'Chaturthi', 'Panchami', 'Shashthi', 'Saptami', 'Ashtami', 'Navami', 'Dashami', 'Ekadashi', 'Dwadashi', 'Trayodashi', 'Chaturdashi', 'Purnima', 'Amavasya'];
    $tithi = $tithis[$dayOfYear % 16];
    
    // Dynamic nakshatra based on date
    $nakshatras = ['Ashwini', 'Bharani', 'Krittika', 'Rohini', 'Mrigashira', 'Ardra', 'Punarvasu', 'Pushya', 'Ashlesha', 'Magha', 'Purva Phalguni', 'Uttara Phalguni', 'Hasta', 'Chitra', 'Swati', 'Vishakha', 'Anuradha', 'Jyeshtha', 'Mula', 'Purva Ashadha', 'Uttara Ashadha', 'Shravana', 'Dhanishtha', 'Shatabhisha', 'Purva Bhadrapada', 'Uttara Bhadrapada', 'Revati'];
    $nakshatra = $nakshatras[$dayOfYear % 27];
    
    // Dynamic yoga based on date
    $yogas = ['Vishkumbha', 'Priti', 'Ayushman', 'Saubhagya', 'Shobhana', 'Atiganda', 'Sukarma', 'Dhriti', 'Shula', 'Ganda', 'Vriddhi', 'Dhruva', 'Vyaghata', 'Harshana', 'Vajra', 'Siddhi', 'Vyatipata', 'Variyan', 'Parigha', 'Shiva', 'Siddha', 'Sadhya', 'Shubha', 'Shukla', 'Brahma', 'Indra', 'Vaidhriti'];
    $yoga = $yogas[$dayOfYear % 27];
    
    // Dynamic karana based on date
    $karanas = ['Bava', 'Balava', 'Kaulava', 'Taitila', 'Gara', 'Vanija', 'Bhadra', 'Shakuni', 'Chatushpada', 'Naga', 'Kinstughna', 'Tavara'];
    $karana = $karanas[$dayOfYear % 12];
    
    // Dynamic muhurat based on day
    $muhurats = ['Brahma Muhurat', 'Abhijit Muhurat', 'Vijaya Muhurat', 'Ravi Muhurat', 'Chandra Muhurat', 'Guru Muhurat', 'Shani Muhurat'];
    $muhurat = $muhurats[$dayOfWeek];
    
    // Dynamic rahu kaal based on day
    $rahuKaals = [
        '7:30 AM - 9:00 AM', '3:00 PM - 4:30 PM', '12:00 PM - 1:30 PM', 
        '1:30 PM - 3:00 PM', '10:30 AM - 12:00 PM', '9:00 AM - 10:30 AM', 
        '4:30 PM - 6:00 PM'
    ];
    $rahuKaal = $rahuKaals[$dayOfWeek];
    
    // Dynamic gulika kaal based on day
    $gulikaKaals = [
        '3:00 PM - 4:30 PM', '12:00 PM - 1:30 PM', '10:30 AM - 12:00 PM',
        '9:00 AM - 10:30 AM', '7:30 AM - 9:00 AM', '6:00 AM - 7:30 AM',
        '4:30 PM - 6:00 PM'
    ];
    $gulikaKaal = $gulikaKaals[$dayOfWeek];
    
    // Dynamic sunrise/sunset based on season
    $month = date('n', strtotime($date));
    if ($month >= 3 && $month <= 5) {
        $sunrise = '06:00 AM';
        $sunset = '06:30 PM';
    } elseif ($month >= 6 && $month <= 8) {
        $sunrise = '05:30 AM';
        $sunset = '07:00 PM';
    } elseif ($month >= 9 && $month <= 11) {
        $sunrise = '06:15 AM';
        $sunset = '06:15 PM';
    } else {
        $sunrise = '06:45 AM';
        $sunset = '05:45 PM';
    }
    
    // Dynamic moonrise/moonset
    $moonrise = date('H:i', strtotime($sunrise . ' +2 hours'));
    $moonset = date('H:i', strtotime($sunset . ' +2 hours'));
    
    // Special days and festivals
    $specialDay = '';
    $festival = '';
    $remarks = 'शुभ दिन';
    
    // Add some special days
    if (date('m-d', strtotime($date)) == '01-15') {
        $specialDay = 'Makar Sankranti';
        $festival = 'Makar Sankranti';
        $remarks = 'विशेष पर्व';
    } elseif (date('m-d', strtotime($date)) == '03-21') {
        $specialDay = 'Holi';
        $festival = 'Holi';
        $remarks = 'रंगों का त्योहार';
    } elseif (date('m-d', strtotime($date)) == '08-15') {
        $specialDay = 'Independence Day';
        $festival = 'Independence Day';
        $remarks = 'राष्ट्रीय पर्व';
    } elseif (date('m-d', strtotime($date)) == '10-02') {
        $specialDay = 'Gandhi Jayanti';
        $festival = 'Gandhi Jayanti';
        $remarks = 'राष्ट्रपिता की जयंती';
    }
    
    return [
        'date' => $date,
        'tithi' => $tithi,
        'nakshatra' => $nakshatra,
        'yoga' => $yoga,
        'karana' => $karana,
        'muhurat' => $muhurat,
        'rahu_kaal' => $rahuKaal,
        'gulika_kaal' => $gulikaKaal,
        'sunrise' => $sunrise,
        'sunset' => $sunset,
        'moonrise' => $moonrise,
        'moonset' => $moonset,
        'special_day' => $specialDay,
        'festival' => $festival,
        'remarks' => $remarks
    ];
}
?>
