from flask import Blueprint, render_template, redirect, url_for, flash, request, send_file, current_app
from flask_login import login_required, current_user
from app import db
from app.models import Document, Project
from werkzeug.utils import secure_filename
import os, uuid
from datetime import datetime

documents_bp = Blueprint('documents', __name__)

ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@documents_bp.route('/')
@login_required
def index():
    doc_type = request.args.get('doc_type', '')
    project_id = request.args.get('project_id', '')
    query = Document.query
    if doc_type:
        query = query.filter_by(doc_type=doc_type)
    if project_id:
        query = query.filter_by(project_id=int(project_id))
    documents = query.order_by(Document.created_at.desc()).all()
    projects = Project.query.all()
    doc_types = ['Kontrak', 'SPM', 'BAST', 'Invoice', 'Faktur Pajak', 'SP2D', 'Surat Jalan', 'Dokumen Teknis', 'Lainnya']
    return render_template('documents/index.html', documents=documents, projects=projects,
                           doc_types=doc_types, current_type=doc_type, current_project=project_id)

@documents_bp.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('Tidak ada file yang dipilih.', 'danger')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '' or not allowed_file(file.filename):
            flash('File tidak valid atau format tidak didukung.', 'danger')
            return redirect(request.url)

        ext = file.filename.rsplit('.', 1)[1].lower()
        unique_name = f"{uuid.uuid4().hex}.{ext}"
        upload_dir = os.path.join(current_app.root_path, '..', current_app.config['UPLOAD_FOLDER'])
        os.makedirs(upload_dir, exist_ok=True)
        file_path = os.path.join(upload_dir, unique_name)
        file.save(file_path)

        doc = Document(
            doc_number=request.form.get('doc_number'),
            doc_name=request.form['doc_name'],
            doc_type=request.form['doc_type'],
            project_id=int(request.form['project_id']) if request.form.get('project_id') else None,
            related_type=request.form.get('related_type'),
            description=request.form.get('description'),
            tags=request.form.get('tags'),
            file_path=unique_name,
            file_name=file.filename,
            file_size=os.path.getsize(file_path),
            file_type=ext,
            uploaded_by=current_user.id
        )
        db.session.add(doc)
        db.session.commit()
        flash(f'Dokumen "{doc.doc_name}" berhasil diunggah!', 'success')
        return redirect(url_for('documents.index'))

    projects = Project.query.all()
    doc_types = ['Kontrak', 'SPM', 'BAST', 'Invoice', 'Faktur Pajak', 'SP2D', 'Surat Jalan', 'Dokumen Teknis', 'Lainnya']
    return render_template('documents/upload.html', projects=projects, doc_types=doc_types)

@documents_bp.route('/download/<int:id>')
@login_required
def download(id):
    doc = Document.query.get_or_404(id)
    upload_dir = os.path.join(current_app.root_path, '..', current_app.config['UPLOAD_FOLDER'])
    file_path = os.path.join(upload_dir, doc.file_path)
    return send_file(file_path, as_attachment=True, download_name=doc.file_name)

@documents_bp.route('/delete/<int:id>', methods=['POST'])
@login_required
def delete(id):
    doc = Document.query.get_or_404(id)
    upload_dir = os.path.join(current_app.root_path, '..', current_app.config['UPLOAD_FOLDER'])
    file_path = os.path.join(upload_dir, doc.file_path)
    if os.path.exists(file_path):
        os.remove(file_path)
    db.session.delete(doc)
    db.session.commit()
    flash('Dokumen berhasil dihapus.', 'success')
    return redirect(url_for('documents.index'))
