import React from 'react'
import {useState, useEffect} from 'react'
import AdminNavbar from './AdminNavbar'

function (){
    const [formData, setFormData] = useState({
        plate_number: "",
        total_seats: "",
        bus_type: ""
    })

    const [buses, setBuses] = useState([])
    const [editBus, setEditBus] = useState(null)

    function handleChange(event){
        const {name, value} = event.target
        setFormData((prev) => ({...prev, [name]: value}))
    }

    function handleEditChange(event){
        const {name, value} = event.target
        setEditBus((prev) => ({...prev, [name]: value}))
    }

    async function handleSubmit(event){
        event.preventDefault()
        if(!formData.plate_number || !formData.total_seats || !formData.bus_type) return alert('Please fill all fields')

        try{
            const response = await fetch("http://localhost:5000/bus", {
                method: "POST",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(formData)
            })
            const data = await response.json()
            if(response.ok){
                alert('Bus created successfully')
                setFormData({plate_number: "", total_seats: "", bus_type: ""})
                fetchBuses()
            }else{
                alert(data.message || 'Failed to create bus')
            }
        }catch(error){
            alert('Server error')
        }
    }

    async function handleUpdate(event){
        event.preventDefault()
        try{
            const response = await fetch("http://localhost:5000/updatebus", {
                method: "PUT",
                headers: {"Content-Type": "application/json"},
                body: JSON.stringify(editBus)
            })
            const data = await response.json()
            if(response.ok){
                alert('Bus updated successfully')
                setEditBus(null)
                fetchBuses()
            }else{
                alert(data.message || 'Failed to update bus')
            }
        }catch(error){
            alert('Server error')
        }
    }

    async function handleDelete(bus_id){
        if(!bus_id){
            alert('Cannot delete: missing bus ID')
            return
        }
        if(!window.confirm('Delete this bus? Related schedules and bookings will also be removed.')){
            return
        }

        try{
            const response = await fetch(`http://localhost:5000/deletebus/${bus_id}`, {
                method: "DELETE"
            })
            const data = await response.json()
            if(response.ok){
                alert('Bus deleted successfully')
                if(editBus?.bus_id === bus_id){
                    setEditBus(null)
                }
                fetchBuses()
            }else{
                alert(data.message || 'Failed to delete bus')
            }
        }catch(error){
            alert('Server error')
        }
    }

    function fetchBuses(){
        fetch("http://localhost:5000/getbus")
        .then(res => res.json())
        .then(data => setBuses(Array.isArray(data) ? data : []))
        .catch(() => alert('Server error'))
    }

    useEffect(() => {
        fetchBuses()
    }, [])

    return(
        <div>
            <AdminNavbar />
            <div className='p-8'>

                <form onSubmit={handleSubmit} className='w-80 p-6 shadow-lg rounded-xl bg-white'>
                    <h2 className='text-2xl font-bold mb-4'>Create Bus</h2>
                    <input
                    name='plate_number'
                    type='text'
                    placeholder='Plate Number'
                    onChange={handleChange}
                    value={formData.plate_number}
                    className='w-full border rounded-xl mb-3 p-3'
                    />
                    <input
                    name='total_seats'
                    type='number'
                    placeholder='Total Seats'
                    onChange={handleChange}
                    value={formData.total_seats}
                    className='w-full border rounded-xl mb-3 p-3'
                    />
                    <input
                    name='bus_type'
                    type='text'
                    placeholder='Bus Type'
                    onChange={handleChange}
                    value={formData.bus_type}
                    className='w-full border rounded-xl mb-3 p-3'
                    />
                    <button type='submit' className='w-full text-white py-2 rounded-xl bg-green-500 hover:bg-green-800'>Create Bus</button>
                </form>

                {editBus && (
                    <form onSubmit={handleUpdate} className='w-80 p-6 mt-6 shadow-lg rounded-xl bg-white'>
                        <h2 className='text-2xl font-bold mb-4'>Update Bus</h2>
                        <input
                        name='plate_number'
                        type='text'
                        onChange={handleEditChange}
                        value={editBus.plate_number}
                        className='w-full border rounded-xl mb-3 p-3'
                        />
                        <input
                        name='total_seats'
                        type='number'
                        onChange={handleEditChange}
                        value={editBus.total_seats}
                        className='w-full border rounded-xl mb-3 p-3'
                        />
                        <input
                        name='bus_type'
                        type='text'
                        onChange={handleEditChange}
                        value={editBus.bus_type}
                        className='w-full border rounded-xl mb-3 p-3'
                        />
                        <button type='submit' className='w-full text-white py-2 rounded-xl bg-blue-500 hover:bg-blue-800'>Save Update</button>
                    </form>
                )}

                <table className='w-full mt-8 bg-white shadow-lg rounded-xl'>
                    <thead>
                        <tr className='bg-green-500 text-white'>
                            <th className='p-3 text-left'>Plate Number</th>
                            <th className='p-3 text-left'>Total Seats</th>
                            <th className='p-3 text-left'>Bus Type</th>
                            <th className='p-3 text-left'>U/D</th>
                        </tr>
                    </thead>
                    <tbody>
                        {buses.map((bus) => (
                            <tr key={bus.bus_id} className='border-b hover:bg-gray-50'>
                                <td className='p-3'>{bus.plate_number}</td>
                                <td className='p-3'>{bus.total_seats}</td>
                                <td className='p-3'>{bus.bus_type}</td>
                                <td className='p-3 flex gap-2'>
                                    <button type='button' onClick={() => setEditBus(bus)} className='px-3 py-1 bg-blue-500 text-white rounded-xl hover:bg-blue-700'>Update</button>
                                    <button type='button' onClick={() => handleDelete(bus.bus_id)} className='px-3 py-1 bg-red-500 text-white rounded-xl hover:bg-red-700'>Delete</button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>

            </div>
        </div>
    )
}

export default Buses2





##Getting shiiiii


import React from 'react'
import {useState, useEffect} from 'react'
import CustomerNavbar from './CutsomerNavbar'

function Buses1(){
    const [buses, setBuses] = useState([])

    function fetchBuses(){
        fetch("http://localhost:5000/getbus")
        .then(res => res.json())
        .then(data => setBuses(Array.isArray(data) ? data : []))
        .catch(() => alert('Server error'))
    }

#####Printing shiiii
    function handlePrint(){
        window.print()
    }

    useEffect(() => {
        fetchBuses()
    }, [])

    return(
        <div>
            <CustomerNavbar />
            <div className='p-8'>

                ####Printing shiiii
                <button onClick={handlePrint} className='px-4 py-2 bg-green-500 text-white rounded-xl hover:bg-green-800'>Print Report</button>

                <table className='w-full mt-8 bg-white shadow-lg rounded-xl'>
                    <thead>
                        <tr className='bg-green-500 text-white'>
                            <th className='p-3 text-left'>Plate Number</th>
                            <th className='p-3 text-left'>Total Seats</th>
                            <th className='p-3 text-left'>Bus Type</th>
                        </tr>
                    </thead>
                    <tbody>
                        {buses.map((bus, index) => (
                            <tr key={index} className='border-b hover:bg-gray-50'>
                                <td className='p-3'>{bus.plate_number}</td>
                                <td className='p-3'>{bus.total_seats}</td>
                                <td className='p-3'>{bus.bus_type}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>

            </div>
        </div>
    )
}

export default Buses1






###############API FOR OPERATING

function getBus(req,res){
    let sql = 'SELECT * FROM buses'

    db.query(sql, (err, rows) => {
        if(err){
            console.log(err)
            return res.status(500).json({message: err.message})
        }
        res.status(200).json(rows)
    })
}

async function deleteBus(req,res){
    const bus_id = req.params.bus_id ?? req.body?.bus_id

    if(!bus_id){
        return res.status(400).json({message: 'bus_id is required'})
    }

    try{
        const [schedules] = await db.execute(
            'SELECT schedule_id FROM schedules WHERE bus_id = ?',
            [bus_id]
        )

        if(schedules.length > 0){
            const scheduleIds = schedules.map((row) => row.schedule_id)
            const placeholders = scheduleIds.map(() => '?').join(',')
            await db.execute(
                `DELETE FROM bookings WHERE schedule_id IN (${placeholders})`,
                scheduleIds
            )
        }

        await db.execute('DELETE FROM schedules WHERE bus_id = ?', [bus_id])
        const [result] = await db.execute('DELETE FROM buses WHERE bus_id = ?', [bus_id])

        if(result.affectedRows === 0){
            return res.status(404).json({message: 'Bus not found'})
        }

        res.status(200).json({message: 'Deleted bus successfully'})
    }catch(err){
        console.log(err)
        res.status(500).json({message: err.message})
    }
}
